Monday, September 9, 2013

Binary Tree Maximum path sum@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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.
» Solve this problem

We need to pay attention on 3 points in this problem:
1. Binary tree
2. It can start and end in any place.
3. The node value can be positive, 0 and negative.

I referred to the solution from Peking2 at MITBBS. The main idea is recursion and DFS.

Analyse the problem, when we are in a root node, how we decided to include the subtree in the maximum path sum? So we need to calculate the max path sum in both subtree. In the meantime, we need to set a variable "max" to store the max path sum we found during the recursion. Pay attention to one thing is, when a root's value is negative, we need to decide include it or discard it.


2 comments:

  1. 这么说来,整棵树可以成为这样的path了么?如果所有节点都是正数的话。

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...