<Interview Problem>二叉树根到叶节点求和值匹配

    题目大意:一颗二叉树,每个节点都有一个Value, 判断根节点到叶节点的路径求和值是否等于某个数Sum.

比如说如下这样一颗二叉树,76是45,21,10这条路径的求和值,77就没有满足条件的路径。

                            45

                    21            65

               10    24      50   70

代码依旧用C++来实现,二叉树一般采用递归的方式来解决。

 

 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

 

 

 

 

posted @ 2013-10-06 14:13  cstar(小乐)  阅读(478)  评论(0编辑  收藏  举报