zoukankan      html  css  js  c++  java
  • Binary Tree Maximum Path Sum

    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.

    Ref:http://fisherlei.blogspot.com/2013/01/leetcode-binary-tree-maximum-path-sum.html

    [Thoughts]
    For each node like following, there should be four ways existing for max path:


    1. Node only
    2. L-sub + Node
    3. R-sub + Node
    4. L-sub + Node + R-sub

    Keep trace the four path and pick up the max one in the end.

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int maxPathSum(TreeNode root) {
            int max[] = new int[1]; 
            max[0] = Integer.MIN_VALUE;
            calculateSum(root, max);
            return max[0];
        }
     
        public int calculateSum(TreeNode root, int[] max) {
            if (root == null)
                return 0;
     
            int left = calculateSum(root.left, max);
            int right = calculateSum(root.right, max);
     
            int current = Math.max(root.val, Math.max(root.val + left, root.val + right));
     
            max[0] = Math.max(max[0], Math.max(current, left + root.val + right));
     
            return current;
        }
    
    }
  • 相关阅读:
    vue组件的通信
    vue基础
    vue项目总结
    路由(4)传参
    路由(3)
    第一次作业
    JAVA-2.0-homework
    JAVA-2.0-上机
    JAVA-1.9-homework
    JAVA-1.9-上机
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3552020.html
Copyright © 2011-2022 走看看