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

Binary Tree Longest Consecutive Sequence

时间:2017-06-07 10:10:51      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:roo   for   binary   val   tree   ges   nbsp   static   amp   

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param root the root of binary tree
     * @return the length of the longest consecutive sequence path
     */
    private static int MAX_LEN = 0; 
    private class ResultType {
        TreeNode curNode;
        int len;
        int maxLen;
        public ResultType(TreeNode curNode, int len) {
            this.curNode = curNode;
            this.len = len;
        }
    } 
    
    public int longestConsecutive(TreeNode root) {
        // Write your code here
        findLongestConsecutive(root);
        return MAX_LEN + 1;
    }
    
    private ResultType findLongestConsecutive(TreeNode root) {
        if (root == null) {
                return new ResultType(null, 0);
        }
        
        ResultType left = findLongestConsecutive(root.left);
        ResultType right = findLongestConsecutive(root.right);
       
        if (left.curNode != null && left.curNode.val - 1 == root.val) {
            left.len += 1;
        } else {
            left.len = 0;
        }
        
        if (right.curNode != null && right.curNode.val - 1 == root.val) {
            right.len += 1;
        } else {
            right.len = 0;
        }
        
        if (left.len > MAX_LEN) {
            MAX_LEN = left.len;
        }
        
        if (right.len > MAX_LEN) {
            MAX_LEN = right.len;
        }
        return new ResultType(root, Math.max(left.len, right.len));
    }
}

 

Binary Tree Longest Consecutive Sequence

标签:roo   for   binary   val   tree   ges   nbsp   static   amp   

原文地址:http://www.cnblogs.com/codingEskimo/p/6955063.html

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