[LeetCode] 549. Binary Tree Longest Consecutive Sequence II_ Medium tag: DFS recursive

Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree.

Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid. On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.

Example 1:

Input:
        1
       / \
      2   3
Output: 2
Explanation: The longest consecutive path is [1, 2] or [2, 1].

Example 2:

Input:
        2
       / \
      1   3
Output: 3
Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].

Note: All the values of tree nodes are in the range of [-1e7, 1e7].

这个题目思路实际上跟 [LeetCode] 124. Binary Tree Maximum Path Sum_ Hard tag: DFS recursive很像, 只是要注意的是当可以两者结合起来的时候, 方向要一致. 

1. Constraints

1) empty => 0

2. Ideas

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

1) edge case

2) helper function, get number of nodes of longest increasing path and longest decreasing path, each time compare self.ans with 1 + li + rd, 1+ ri + ld

3) return self.ans

3. Code

 1 class Solution:
 2     def longestConsecutive2(self, root):
 3         self.ans = 0
 4         def helper(root):
 5             if not root: return 0, 0
 6             li, ld = helper(root.left)
 7             ri, rd = helper(root.right)
 8             li = li if li and root.left.val + 1 == root.val else 0
 9             ld = ld if ld and root.left.val - 1 == root.val else 0
10             ri = ri if ri and root.right.val + 1 == root.val else 0
11             rd = rd if rd and root.right.val -1 == root.val else 0
12             self.ans = max(self.ans, 1+ li + rd, 1 + ri + ld)
13             return 1+ max(li, ri), 1+ max(ld + rd)
14         helper(root)
15         return self.ans

4. Test cases

1)empty 

2) 1

3) 

        2
       / \
      1   3

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9327261.html
今日推荐