LeetCode- Binary Tree Longest Consecutive Sequence

LiBlog發表於2016-08-21

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.

Solution:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public class ConsLen {
12         int fromMe;
13         int fromBelow;
14 
15         public ConsLen(int m, int b){
16             fromMe = m;
17             fromBelow = b;
18         }
19     }
20 
21     public int longestConsecutive(TreeNode root) {
22         if (root==null) return 0;
23             
24         ConsLen res = findConsecutiveSeq(root);
25 
26         return Math.max(res.fromMe,res.fromBelow);
27     }
28 
29     public ConsLen findConsecutiveSeq(TreeNode cur){
30         if (cur.left==null && cur.right==null){
31             return new ConsLen(1,0);
32         }
33 
34         ConsLen res = new ConsLen(1,0);
35         if (cur.left!=null){
36             ConsLen leftRes = findConsecutiveSeq(cur.left);
37             if (cur.left.val == cur.val+1){
38                 res.fromMe = leftRes.fromMe + 1;
39             }
40             res.fromBelow = Math.max(leftRes.fromMe, leftRes.fromBelow);
41         }
42 
43         if (cur.right!=null){
44             ConsLen rightRes = findConsecutiveSeq(cur.right);
45             if (cur.right.val == cur.val+1){
46                 res.fromMe = Math.max(res.fromMe,rightRes.fromMe+1);
47             }    
48             res.fromBelow = Math.max(res.fromBelow,Math.max(rightRes.fromMe,rightRes.fromBelow));
49         }
50         
51         return res;
52     }
53 }

 

相關文章