码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode- Binary Tree Longest Consecutive Sequence

时间:2016-08-21 15:10:35      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

LeetCode- Binary Tree Longest Consecutive Sequence

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/5792744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!