[leetcode] 124. 二叉树中的最大路径和

124. 二叉树中的最大路径和

二叉树问题往往都可以归结到二叉树的三种遍历上。
此题也不例外,仔细分析后发现其实就是二叉树的后续遍历。

问题解法很简单:
枚举树中的每一个节点为根节点,求出该节点的最大路径和。当遍历完成整棵树后,全局的最大路径和便就能找出来了。

关键在于怎么求节点的最大路径和。

观察发现,路径和 = 左子树最大路径 + 节点值 + 右子树最大路径。
那么,求路径和问题就可以利用递归思想来做了。

class Solution {
    int ans = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        dfs(root);
        return ans;
    }

    public int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = dfs(root.left);
        if (left < 0) {
            left = 0;
        }
        int right = dfs(root.right);
        if (right < 0) {
            right = 0;
        }
        ans = Math.max(ans, root.val + left + right);
        return root.val + Math.max(left, right);
    }
}

猜你喜欢

转载自www.cnblogs.com/acbingo/p/10644610.html