binary_tree_maxPathSum

题目描述
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


Return6.

import java.util.*;


public class binary_tree_maxPathSum {
	 static int max_val=0; 
	 public static void main(String[] args) {
		 TreeNode a= new TreeNode(1);
		 TreeNode b= new TreeNode(-2);
		 TreeNode c= new TreeNode(3);
		 a.left=b;
		 a.right=c;
		 max_val=Integer.MIN_VALUE;
		 maxPathSum(a);
		 System.out.println(max_val);
	 }
	 
	 public static int maxPathSum(TreeNode root) {
	     if(root==null) {
	    	 return 0;
	     }
	     // 左子树最大路径 (小于0 则为0) 
	     int l=Math.max(0, maxPathSum(root.left)) ;
	     // 右子树最大路径(小于0 则为0)
	     int r=Math.max(0, maxPathSum(root.right)) ;
	     // 以当前节点作为根节点,则最大路径为 左+右+根
	     max_val=Math.max(max_val,l+r+root.val );
	     // 作为上一层节点的左/右子树 返回值 只能是左+根  \ 右+根 中最大的
		 return Math.max(0, root.val+Math.max(l, r));
	    }
	 
	 
	 
 }
	      


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值