zoukankan      html  css  js  c++  java
  • [LeetCode] 124. Binary Tree Maximum Path Sum 求二叉树的最大路径和

    Given a non-empty binary tree, find the maximum path sum.

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

    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

    给一个非空二叉树,找出最大路径和。

    解法:递归,与常规path sum不同,这题的path sum可以不起始于root,也可以不终止于leaf。

    Java:

    public class Solution {
        int maxValue;
        
        public int maxPathSum(TreeNode root) {
            maxValue = Integer.MIN_VALUE;
            maxPathDown(root);
            return maxValue;
        }
        
        private int maxPathDown(TreeNode node) {
            if (node == null) return 0;
            int left = Math.max(0, maxPathDown(node.left));
            int right = Math.max(0, maxPathDown(node.right));
            maxValue = Math.max(maxValue, left + right + node.val);
            return Math.max(left, right) + node.val;
        }
    }
    

    Python:

    # Time:  O(n)
    # Space: O(h), h is height of binary tree
    
    class TreeNode(object):
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    
    class Solution(object):
        maxSum = float("-inf")
    
        # @param root, a tree node
        # @return an integer
        def maxPathSum(self, root):
            self.maxPathSumRecu(root)
            return self.maxSum
    
        def maxPathSumRecu(self, root):
            if root is None:
                return 0
            left = max(0, self.maxPathSumRecu(root.left))
            right = max(0, self.maxPathSumRecu(root.right))
            self.maxSum = max(self.maxSum, root.val + left + right)
            return root.val + max(left, right) 

    C++:

    class Solution {
    public:
        int maxPathSum(TreeNode* root) {
            int res = INT_MIN;
            helper(root, res);
            return res;
        }
        int helper(TreeNode* node, int& res) {
            if (!node) return 0;
            int left = max(helper(node->left, res), 0);
            int right = max(helper(node->right, res), 0);
            res = max(res, left + right + node->val);
            return max(left, right) + node->val;
        }
    };
    

      

    Follow up: 返回最大路径,递归函数就不能返回路径和,而是返回该路径上所有结点组成的数组,递归的参数还要保留最大路径和,对左右子节点调用递归函数后得到的是数组,统计出数组之和,并且跟0比较,如果小于0,和清零,数组清空。

    类似题目:

    [LeetCode] 112. Path Sum 路径和

    [LeetCode] 113. Path Sum II 路径和 II

    [LeetCode] 437. Path Sum III 路径和 III 

    [LeetCode] 666. Path Sum IV 二叉树的路径和 IV

    [LeetCode] 687. Longest Univalue Path 最长唯一值路径

    [LeetCode] 129. Sum Root to Leaf Numbers 求根到叶节点数字之和

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    Java原始数据类型
    Java文件教程
    Java.util.ArrayDeque类
    Java 简介
    面向对象的程序设计
    Java8默认方法
    divide方法
    java.lang.Boolean.compareTo()方法实例
    AWT Button类
    Java的核心优势
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9801775.html
Copyright © 2011-2022 走看看