Binary Tree Maximum Path Sum --- LeetCode

来源:互联网 发布:第十四届网络夏令营 编辑:程序博客网 时间:2024/05/22 00:27

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.

解题思路:  题目要求:找出一棵二叉树上的一条路径,该路径上的节点值和为最大,输出这个最大值。

                解题思路:遍历二叉树,从下到上递归计算每个节点的最大值:

                                 max{节点值,节点值+左子树,节点值+右子树,节点值+左右子树}

                                 记录最大值maxValue, 同时将以该节点为头结点的路径最大值返回,递归计算上一层节点:

                                             max{节点值,节点值+左子树,节点值+右子树}

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private int maxValue=0;

public int maxSum(TreeNode node){
if(node==null){
  return 0;
}
int value=node.val;
int leftSum=0;
int rightSum=0;
if(node.left!=null){
   leftSum=maxSum(node.left);
if(leftSum>0){
  value+=leftSum;
}
}
if(node.right!=null){
rightSum=maxSum(node.right);
   if(rightSum>0){
      value+=rightSum;
   }
}
if(value>maxValue){
maxValue=value;
}

return Math.max(node.val, Math.max(node.val+leftSum, node.val+rightSum));

}


    public int maxPathSum(TreeNode root) {
         if(root==null){
        return 0;
         }
         maxValue=root.val;
         maxSum(root);
    return maxValue;       
    } 
    
}

0 0
原创粉丝点击