首页 > 代码库 > Binary Tree Longest Consecutive Sequence

Binary Tree Longest Consecutive Sequence

/**
 * 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