leetcode Binary Tree Maximum Path Sum

来源:互联网 发布:非农数据最新消息 编辑:程序博客网 时间:2024/06/13 12:22

Given a 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 does not need to go through the root.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.

需要设置一个全局变量max来更新path sum的最大值,因为max path可能发生在任何点和路径,代码:

private int max=Integer.MIN_VALUE;public int maxPathSum(TreeNode root) {    getMax(root);       return max;}public int getMax(TreeNode root){    if(root==null) return 0;    int val=root.val;    int leftMax=getMax(root.left);    if(leftMax>0) val+=leftMax;    int rightMax=getMax(root.right);    if(rightMax>0) val+=rightMax;    if(val>max) max=val;    return Math.max(root.val+leftMax,Math.max(root.val+rightMax,root.val));}

0 0