Monday, November 2, 2015

[leetcode]Binary Tree Longest Consecutive Sequence

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int longestConsecutive(TreeNode root) {
        if (root == null) return 0;
        return Math.max(recurLongest(root.left, root.val, 1), 
                        recurLongest(root.right, root.val, 1));
    }

    private int recurLongest(TreeNode root, int parentVal, int lengthSoFar){
     if (root == null) return lengthSoFar;
     if (root.val == parentVal+1) return Math.max(recurLongest(root.left, root.val, lengthSoFar+1), 
                recurLongest(root.right, root.val, lengthSoFar+1));
     int rec = Math.max(recurLongest(root.left, root.val, 1), 
            recurLongest(root.right, root.val, 1));
     return Math.max(lengthSoFar, rec);
    }
}

No comments:

Post a Comment