Leetcode 298: Binary Tree Longest Consecutive Sequence

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).

For example,

   1
    \
     3
    / \
   2   4
        \
         5

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

   2
    \
     3
    / 
   2    
  / 
 1

Longest consecutive sequence path is 2-3,not3-2-1, so return 2.

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int LongestConsecutive(TreeNode root) {
12         if (root == null) return 0;
13         var max = new int[1] {1} ;
14         DFS(root.left, root.val, 1, max);
15         DFS(root.right, root.val, 1, max);
16         
17         return max[0];
18     }
19     
20     private void DFS(TreeNode node, int prev, int len, int[] max)
21     {
22         if (node == null) return;
23         
24         if (node.val == prev + 1)
25         {
26             len++;
27             max[0] = Math.Max(max[0], len);
28             
29             DFS(node.left, node.val, len, max);
30             DFS(node.right, node.val, len, max);
31         }
32         else
33         {
34             max[0] = Math.Max(max[0], len);
35             
36             DFS(node.left, node.val, 1, max);
37             DFS(node.right, node.val, 1, max);
38         }
39     }
40 }

 

posted @ 2017-12-20 06:56  逸朵  阅读(126)  评论(0)    收藏  举报