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.
递归思路,依次访问每个节点,记录根到叶子的总和,然后全部相加即可。
压栈思路:先左节点全入,和依次递增,然后左出右入。这里只需要用和运算来判断,因为需要找所有路径的总和。
注意:第一次压栈应该压入helper(root, 0), 而不是helper(root, root.val),因为后者会让root.left(root.right)与求和的root.left处于同一个等级,空指针不可避免。而前者是让root.left(root.right)与求和的root处于同一个等级,可以有效避免空指针问题。
public int sumNumbers(TreeNode root) {
if(root==null)
return 0;
return helper(root, 0);
}
public int helper(TreeNode root, int sum) {
if(root==null)
return 0;
if(root.left==null&&root.right==null)
return sum*10+root.val;
int left=helper(root.left, sum*10+root.val);
int right=helper(root.right, sum*10+root.val);
return left+right;
}

本文介绍了一种解决二叉树最大路径和问题的方法。通过递归遍历每个节点并记录从根节点到叶子节点的路径总和,最终找出最大的路径和。文章详细解释了递归思路,并给出了具体的实现代码。

272

被折叠的 条评论
为什么被折叠?



