Binary Tree Maximum Path Sum

题目链接:https://leetcode.com/problems...

dfs对每个node,查一下包含这个node的最大路径值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxPathSum(TreeNode root) {
        dfs(root);
        return globalMax;
    }
    
    int globalMax = Integer.MIN_VALUE;
    private int dfs(TreeNode root) {
        // base case
        if(root == null) return 0;
        
        int left = Math.max(0, dfs(root.left));
        int right = Math.max(0, dfs(root.right));
        
        globalMax = Math.max(globalMax, left + right + root.val);
        
        return Math.max(left, right) + root.val;
    }
}

lulouch13
13 声望6 粉丝

« 上一篇
Diagonal traverse
下一篇 »
Perfect Rectangle