[Leetcode] [JAVA] Binary Tree Maximum Path Sum

Source: Internet
Author: User

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 .


For the tree, we can find the maximum path value that terminates at the root node in its left and right subtree, called the maximum half-path value, and if it is a positive number, you can add them together with the root node value, and if there are negative numbers, discard the value on that side (that is, set to 0). This allows you to find the maximum path value that contains the root node. Then select the largest half path value of the left and right subtree (negative number is set to 0) plus the value of the root node as the new maximum half path value passed to the parent node.

So we can review each subtree recursively, updating a global variable max.

The basic case is: The subtree is null, at which point the maximum path value should be 0.

The code is as follows:

1     intMax;2      Public intmaxpathsum (TreeNode root) {3max = root==NULL? 0: Root.val;4 Findmax (root);5         returnMax;6     }7      Public intFindmax (TreeNode root) {8         if(root==NULL)9             return0;Ten         intleft = Math.max (Findmax (root.left), 0); One         intright = Math.max (Findmax (root.right), 0); Amax = Math.max (max, left+right+root.val); -         returnMath.max (left, right) +Root.val; -}

[Leetcode] [JAVA] Binary Tree Maximum Path Sum

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.