Longest Consecutive Sequence in Binary Tree

This Java code defines a Solution class with methods to find the length of the longest consecutive sequence of nodes in a binary tree. It includes a main method and a helper method.
mail@pastecode.io avatar
unknown
java
a month ago
828 B
2
Indexable
Never
public class Solution {
	public int longestConsecutive(TreeNode root) {
		//You can code here

		if(root==null)
		return 0;
    int count=1;
		return Math.max(longestConsecutiveHelper(root.left,count),longestConsecutiveHelper(root.right,count));     
	}

	public int longestConsecutiveHelper(TreeNode node, int count){

		if(node==null)
		return count;


		int leftCount=0;
		int rightCount=0;


		if(node.left==null && node.right==null)
		{
			return count;
		}

		if(node.left!=null)
		{
			if(node.left.val-node.val==1)
			{
				leftCount=longestConsecutiveHelper(node.left,count+1);
			}
		}

		if(node.right!=null)
		{
			if(node.right.val-node.val==1)
			{
				rightCount=longestConsecutiveHelper(node.right,count+1);
			}
		}

		return Math.max(leftCount+1,rightCount+1);
	}

}
Leave a Comment