Binary Tree Longest Consecutive Sequence07/26

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).Have you met this question in a real interview? Yes

Example

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 of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root of binary tree
     * @return: the length of the longest consecutive sequence path
     */
    public int longestConsecutive(TreeNode root) {
        // write your code here
        
        int res = helper(root,null,0);
        
        return res;
    }
    
    public int helper(TreeNode root,TreeNode parent, int l){
        if(root == null){
            return 0;
        }
        
        int length = (parent != null && parent.val+1 == root.val) ? l+1: 1;
        
        int leftLength = helper(root.left,root,length);
        int rightLength = helper(root.right,root,length);
        
        return Math.max(length,Math.max(leftLength,rightLength));
    }
}

Last updated