码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 124. Binary Tree Maximum Path Sum

时间:2020-03-18 15:15:37      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:时间   @param   new   turn   log   post   corn   输出   题意   

二叉树的最大路径和。题意是给一个二叉树,节点是数字,请输出一个最大的路径和。例子,

Example 1:

Input: [1,2,3]

       1
      /      2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   /   9  20
    /     15   7

Output: 42

注意第二个例子,节点值是会存在负数的。思路是后序遍历,因为路径和总是要包括左孩子val + 右孩子val + 当前节点val。做法跟其他后序遍历的题几乎都一样,也是创建一个全局变量记录最后的结果。helper函数里面去递归左子树和右子树的时候,记得是跟0比较谁大,因为节点值包括负数。res算的是root.val + left + right。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     int res;
 3 
 4     public int maxPathSum(TreeNode root) {
 5         // corner case
 6         if (root == null) {
 7             return 0;
 8         }
 9         res = Integer.MIN_VALUE;
10         helper(root);
11         return res;
12     }
13 
14     public int helper(TreeNode root) {
15         if (root == null) {
16             return 0;
17         }
18         int left = Math.max(0, helper(root.left));
19         int right = Math.max(0, helper(root.right));
20         res = Math.max(res, left + right + root.val);
21         return Math.max(left, right) + root.val;
22     }
23 }

 

JavaScript实现

 1 /**
 2  * @param {TreeNode} root
 3  * @return {number}
 4  */
 5 var maxPathSum = function (root) {
 6     let res = -Infinity;
 7     let helper = function (root) {
 8         if (root == null) return 0;
 9         let left = Math.max(0, helper(root.left));
10         let right = Math.max(0, helper(root.right));
11         // let newPath = root.val + left + right;
12         res = Math.max(root.val + left + right, res);
13         return Math.max(left, right) + root.val;
14     }
15     helper(root);
16     return res;
17 };

 

[LeetCode] 124. Binary Tree Maximum Path Sum

标签:时间   @param   new   turn   log   post   corn   输出   题意   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12517278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!