GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/binary-tree-maximum-path-sum at gh-pages · codingwhite/leetcode

Expand file tree

/

binary-tree-maximum-path-sum

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
 
 
/

binary-tree-maximum-path-sum

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
README.md
README.md
 
 
Solution.java
Solution.java
 
 
index.md
index.md
 
 

README.md

Outline

What will the maximum path look like

Though paths can be starting from any node and end at any node, the appearances only can be:

  • Appearance 1
      *
     / \
    *   *
   /     \ 
  *       *
 /         \ 
S           *
             \
              E
  • Appearance 2
      E
     / 
    * 
   / 
  * 
 / 
S           
  • Appearance 3
S
 \
  *
   \
    *
     \
      *
       \
        E         

Note

Appearances above are only talking about TRUNK.

Treat the path below as Appearance 1

      *
     / \
    *   *
   /     \
  *       *
   \     /
    S   *
         \
          E

Tree Version of Maximum Subarray

  • Appearance 2/3

These two appearances are easy to understand and to build a path, just take the maximum node. like Maximum Subarray, if the sum goes below 0, forget the old nodes.

  • Appearance 1

If a node's left child or right child is less than 0, drop it, then the node becomes Appearance 2/3.

If both the left child and right child are positive, just add them together, maxPathSum(node.left) + node.val + maxPathSum(node.right) will be the maxPathSum which contains that node.

Put them together

As we know how to find the maxPathSum of any node, we can go through the tree and update the max value.

You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.