[LeetCode] 298. Binary Tree Longest Consecutive Sequence

二叉树最长连续序列。题意是给一个二叉树,求出其最长的连续序列。例子如下,

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.

这个题我给出DFS的解法,同样也是先序遍历。

时间O(n)

空间O(n)

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {number}
11  */
12 var longestConsecutive = function(root) {
13     return helper(root);
14 };
15 
16 var helper = function(node, prev, count) {
17     if (!node) {
18         return count || 0;
19     }
20     if (node.val === prev + 1) {
21         count++;
22     } else {
23         count = 1;
24     }
25     let res = Math.max(
26         count,
27         helper(node.left, node.val, count),
28         helper(node.right, node.val, count)
29     );
30     return res;
31 };

你可能感兴趣的:([LeetCode] 298. Binary Tree Longest Consecutive Sequence)