[leetcode]Binary Tree Maximum Path Sum - java 后续遍历

这道题估计难在审题上,题目描述太简单了,导致提交各种情况没想到,整个代码比较简单,可以解释题目,采用递归后续遍历的方式,从叶子节点开始算起,每次计算产生两个值,一个是最大通路值(maxPathSum ),一个是子树能为父节点提供的最大单支值(findSingleBranchMaxPathSum递归返回的值)

 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private Integer maxPathSum = null;

    public int maxPathSum(TreeNode root){
        findSingleBranchMaxPathSum(root);
        return maxPathSum;
    }

    private int findSingleBranchMaxPathSum(TreeNode root) {
        int leftMaxPathSum=0;
        int rightMaxPathSum=0;
        if(root.left != null){
            leftMaxPathSum = findSingleBranchMaxPathSum(root.left);
        }
        if(root.right != null){
            rightMaxPathSum = findSingleBranchMaxPathSum(root.right);
        }
        int left = leftMaxPathSum<0?0:leftMaxPathSum;
        int right = rightMaxPathSum<0?0:rightMaxPathSum;
        if(maxPathSum == null){
            maxPathSum = root.val+left+right;
        }else if(root.val+left+right>maxPathSum){
            maxPathSum = root.val+left+right;
        }
        int single = left>right?left:right;
        return root.val+single;
    }
}

 

 

 

你可能感兴趣的:(LeetCode,算法)