二叉樹根到葉節點求和值匹配

    題目大意:一顆二叉樹,每一個節點都有一個Value, 判斷根節點到葉節點的路徑求和值是否等於某個數Sum.node

好比說以下這樣一顆二叉樹,76是45,21,10這條路徑的求和值,77就沒有知足條件的路徑。ios

                            45ide

                    21            65spa

               10    24      50   70code

代碼依舊用C++來實現,二叉樹通常採用遞歸的方式來解決。blog

 

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 typedef struct BTree
 6 
 7 {
 8         int value;
 9         struct BTree* left;
10         struct BTree* right;
11 } BTree;
12 typedef struct BTree Node;
13 
14 //recursively insert a tree node   
15 
16 BTree* Insert(BTree* T, int value)
17 {
18       if(T == NULL)
19       {
20         T = (BTree*)malloc(sizeof(struct BTree));
21         if(T == NULL)
22                 printf("Malloc failed");
23         else{
24                 T->value = value;
25                 T->left = T->right = NULL;
26         }
27       }
28       else if(value < T->value)
29         T->left = Insert(T->left,value);
30       else if(value > T->value)
31         T->right = Insert(T->right,value);
32       return T;
33 }
34 BTree* MakeEmpty(BTree* T)
35 {
36         if(T != NULL){
37                 MakeEmpty(T->left);
38                 MakeEmpty(T->right);
39                 free(T);
40         }
41         return NULL;
42 }
43 
44 
45 bool hasPathSum( Node *node, int sum, int pathSum)
46 {
47         bool match = false;
48         if(node != NULL)
49                 pathSum += node->value;
50         if(node->left== NULL && node->right == NULL)
51         {
52                 if(sum == pathSum)
53                         match = true;
54                 else
55                         match = false;
56         }
57         if(node->left != NULL && !match)
58                 match = hasPathSum(node->left,sum,pathSum);
59         if(node->right != NULL && !match)
60                 match = hasPathSum(node->right,sum,pathSum);
61         return match;
62 }
63 bool hasPathSum( Node *root, int sum)
64 {
65         if(root == NULL) return false;
66          bool match = false;
67          match = hasPathSum(root,sum,0);
68          return match;
69 }
70 int main()
71 {
72         BTree* T = NULL;
73         T = Insert(T,45);
74         T = Insert(T,21);
75         T = Insert(T,65);
76         T = Insert(T,10);
77         T = Insert(T,50);
78         T = Insert(T,70);
79         T = Insert(T,24);
80         bool match = hasPathSum(T,76);
81         cout << match << endl;
82         match = hasPathSum(T,77);
83         cout << match << endl;
84         MakeEmpty(T);
85         return 0;
86 }
View Code
相關文章
相關標籤/搜索