代码改变世界

[LeetCode] 298. Binary Tree Longest Consecutive Sequence_Medium tag: DFS recursive

2018-07-18 06:44  Johnson_强生仔仔  阅读(205)  评论(0编辑  收藏  举报

Given a binary tree, find the length of the longest consecutive sequence path.

The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).

Example 1:

Input:

   1
    \
     3
    / \
   2   4
        \
         5

Output: 3

Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

Input:

   2
    \
     3
    / 
   2    
  / 
 1

Output: 2 

Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

这个题目思路跟[LeetCode] 687. Longest Univalue Path_Easy tag: DFS recursive, 但实际上比它还简单, 因为不需要验证l + root + r, 但是也只是self.ans 里面少加一个判断而已, 本质一样, 用helper function, 得到包括root 的最大的increasing consecutive path 的 number of nodes, 并且每次跟self.ans 比较, 最后return self.ans.

 

1. Constraints

1) empty => 0

2) element will be intergeres

 

2) Ideas

DFS    T; O(n)    S: O(n)

 

3) code

class Solution:
    def longestConsecutive(self, root):
        ans = [0]
        def longestConsecutiveWithRoot(root):
            if not root: return 0
            l, r = longestConsecutiveWithRoot(root.left), longestConsecutiveWithRoot(root.right)
            l = l if root.left and root.left.val - 1 == root.val else 0
            r = r if root.right and root.right.val - 1 == root.val else 0
            local = 1 + max(l, r)
            ans[0] = max(ans[0], local)
        longestConsecutiveWithRoot(root)
        return ans[0]

 

4. Test cases

   1
    \
     3
    / \
   2   4
        \
         5