2015年10月28日星期三

Binary Tree Longest Consecutive Sequence

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.

 /**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   
    private int maxLen = 0;
   
    public int longestConsecutive(TreeNode root) {
        maxLen = 0;
        if (root == null) {
            return maxLen;
        }
        helper(root, 1);
        return maxLen;
    }
   
    private void helper(TreeNode node, int len) {
        if (node == null) return;
        maxLen = Math.max(maxLen, len);
        if (node.left != null) {
            if (node.left.val == node.val + 1) {
                helper(node.left, len + 1);
            } else {
                helper(node.left, 1);
            }
        }
        if (node.right != null) {
            if (node.right.val == node.val + 1) {
                helper(node.right, len + 1);
            } else {
                helper(node.right, 1);
            }
        }
    }
}

没有评论:

发表评论