549 Binary Tree Longest Consecutive Sequence II

549. Binary Tree Longest Consecutive Sequence II

1. Question

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:

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

2. Implementation

(1) DFS

思路:对于每个node,我们分别找出它的左子树和右子树中最长的increasing consecutive sequence的长度和decreasing consecutive sequence的长度, 然后这两个长度加起来减一(该node被重复算了一次),则是穿过这个node的最长consecutive sequence,通过这个方法,递归地遍历每个node可以得到最后的结果

3. Time & Space Complexity

DFS: 时间复杂度: O(n), 空间复杂度: O(n)

Last updated

Was this helpful?