zoukankan      html  css  js  c++  java
  • Leetcode: 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.

    难度:75. 

    参见了他人的思路,这道题是求树的路径和的题目,不过和平常不同的是这里的路径不仅可以从根到某一个结点,而且路径可以从左子树某一个结点,然后到达右子树的结点,就像题目中所说的可以起始和终结于任何结点。函数的返回值定义为以自己为根的一条从根到叶子结点的最长路径,这个返回值是为了提供给它的父结点计算自身的最长路径用。这样一来,一个结点自身的最长路径就是它的左子树返回值(如果大于0的话),加上右子树的返回值(如果大于0的话),再加上自己的值。在过程中求得当前最长路径时比较一下是不是目前最长的,如果是则更新。算法的本质还是一次树的遍历,所以复杂度是O(n)。而空间上仍然是栈大小O(logn)。注意这里path的存值方式是个问题,如果用一个integer变量代入recursion的话,函数无法对实参造成改变,所以用了一个对象ArrayList<Integer> res的第一个元素来存最大的path值

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int maxPathSum(TreeNode root) {
    12         if (root == null) return 0;
    13         ArrayList<Integer> res = new ArrayList<Integer>();
    14         res.add(Integer.MIN_VALUE);
    15         FindMaxSum(root, res);
    16         return res.get(0);
    17     }
    18     
    19     public int FindMaxSum(TreeNode root, ArrayList<Integer> res) {
    20         if (root == null) {
    21             return 0;
    22         }
    23         int leftsum = FindMaxSum(root.left, res);
    24         int rightsum = FindMaxSum(root.right, res);
    25         int maxsum = root.val + (leftsum>0? leftsum : 0) + (rightsum>0? rightsum : 0);
    26         if (maxsum > res.get(0)) res.set(0, maxsum);
    27         return root.val + Math.max(leftsum, Math.max(rightsum, 0));
    28     }
    29 }

     Or we can use external variable

     1 class Solution {
     2     int maxSum = Integer.MIN_VALUE;
     3     public int maxPathSum(TreeNode root) {
     4         helper(root);
     5         return maxSum;
     6     }
     7     
     8     public int helper(TreeNode node) {
     9         if (node == null) return 0;
    10         int left = helper(node.left);
    11         int right = helper(node.right);
    12         maxSum = Math.max(maxSum, node.val + (left > 0 ? left : 0) + (right > 0 ? right : 0));
    13         return node.val + Math.max(0, Math.max(left, right));
    14     }
    15 }
  • 相关阅读:
    leetcode
    Vim i和a差别
    HDU-4643-GSM(DFS)
    使用可编程电源自动化输出电源
    如何使用全局变量
    异步和同步
    启动界面
    鼠标右键弹出菜单
    Qt+excel
    Qt+数据库
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3961296.html
Copyright © 2011-2022 走看看