找出二叉树中和最大的路径,路径可以从任意节点开始,到任意节点结束。

来源:互联网 发布:sqoop导入数据到hbase 编辑:程序博客网 时间:2024/05/17 15:38

    题目:leetcode

    Given a binary tree, find the maximum path sum.

    The path may start and end at any node in the tree. For example: Given the below binary tree,
     1
     / \

   2  3

Return 6.

    提示:路径可以从任意节点开始,到任意节点结束。可以利用“最大连续子序列和”问题的思路,点击打开链接。如果说Array 只有一个方向的话,那么Binary Tree 其实只是左、右两个方向而已,我们需要比较两个方向上的值。不过,Array 可以从头到尾遍历,那么Binary Tree 怎么办呢,我们可以采用Binary Tree 最常用的DFS 来进行遍历。先算出左右子树的结果L 和R,如果L 大于0,那么对后续结果是有利的,我们加上L,如果R 大于0,对后续结果也是有利的,继续加上R。

    

bool g_IsRight=true;int MaxPathSum_Core(int &maxnum,TreeNode* root){if(root==nullptr)return -1;int sum=root->val;int l=MaxPathSum_Core(maxnum,root->left);int r=MaxPathSum_Core(maxnum,root->right);if(l>0)sum+=l;if(r>0)sum+=r;maxnum=max(maxnum,sum);if(max(l,r)>0)return max(l,r)+root->val;elsereturn root->val;}int MaxPathSum(TreeNode *root){ g_IsRight=true;if(root==nullptr){ g_IsRight=false; return 0;}int maxnum=root->val;MaxPathSum_Core(maxnum,root);return maxnum;}

    注意在返回值无法表达输入不合法的情况时,加一个全局变量进行标志。MaxPathSum_Core最后return 的时候,只返回一个方向上的值,为什么?这是因为在递归中,只能向父节点返回,不可能存在L->root->R 的路径,只可能是L->root 或R->root。

0 0
原创粉丝点击