Binary Tree Maximum Path Sum 个人思路小计

最近有点兴趣想写点博客,增加点生活啊,学习的乐趣,算是个记录吧,今天先写个算法的。

Binary Tree Maximum Path Sum求2叉树随意路径的最大值

看到二叉树的题目首先想到的肯定是递归了,二叉树的递归很好理解,一般就是分成左子树右子树呗,然后对

求得的结果进行总结一下。这里我就假设我求的了到左根节点的最大值,到右根节点的最大值,然后要求的最

大值应该有6种情况

1.就是根节点

2.根节点+左子树最大

3.根节点+右子树最大

4.右子树最大

5.左子树最大

6.根+左+右

有了这个就很好递归了,中间用个全局变量把所有的最大值记录起来。这里要注意子树节点为空时候的求值,因为

涉及到最大,最小,具体看代码。

 1 struct TreeNode {
 2       int val;
 3       TreeNode *left;
 4       TreeNode *right;
 5       TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 6  };
 7 int ans = INT_MIN;
 8 
 9 int getmax(int a,int b)
10 {
11     return a>=b?a:b;
12 }
13 int maxPathSumToRoot(TreeNode* root,int &ans)
14 {
15         if(root->left == NULL && root->right == NULL)
16         {
17             return root->val;
18         }
19         bool has_l = false;
20         bool has_r = false;
21         int maxL = INT_MIN;
22         int maxR = INT_MIN;
23         if(root->left)
24         {
25             has_l = true;
26             maxL = maxPathSumToRoot(root->left,ans);
27         }
28         if(root->right)
29         {
30             has_r = true;
31             maxR = maxPathSumToRoot(root->right,ans);
32         }
33         ans = getmax(ans,root->val);
34         if(has_l)
35         {
36             ans = getmax(ans,maxL);
37             ans = getmax(ans,maxL+root->val);
38         }
39         if(has_r)
40         {
41             ans = getmax(ans,maxR);
42             ans = getmax(ans,maxR+root->val);
43         }
44         if(has_l && has_r)
45         {
46             ans = getmax(ans,maxL+maxR+root->val);
47         }
48         int curMax = root->val;
49         if(has_l)
50         {
51             curMax = getmax(curMax,root->val+maxL);
52         }
53         if(has_r)
54         {
55             curMax = getmax(curMax,root->val+maxR);
56         }
57         return curMax;
58 }
59 int maxPathSum(TreeNode* root)
60 {
61         if(root == NULL)return 0;
62         if(root->left == NULL && root->right == NULL)
63         {
64             return root->val;
65         }
66         maxPathSumToRoot(root,ans);
67         return ans;
68 }
69 int _tmain(int argc, _TCHAR* argv[])
70 {
71     TreeNode *root = new TreeNode(1);
72     TreeNode *node2 = new TreeNode(-2);
73     TreeNode *node3 = new TreeNode(-3);
74     TreeNode *node4 = new TreeNode(1);
75     TreeNode *node5 = new TreeNode(3);
76     TreeNode *node6 = new TreeNode(-2);
77     TreeNode *node7 = new TreeNode(1);
78     root->left = node2;
79     root->right = node3;
80     node2->left = node4;
81     node2->right = node5;
82     node3->left = node6;
83 //    node3->right = node7;
84     node4->left = node7;
85     cout<<maxPathSum(root)<<endl;
86     return 0;
87 }

 

posted @ 2015-05-11 20:11  梅开二度  阅读(153)  评论(0)    收藏  举报