298. Binary Tree Longest Consecutive Sequence
Explanation:
- We need to find the length of the longest consecutive sequence path in a binary tree.
- A consecutive sequence is a sequence of nodes from parent to child where the values of the nodes are consecutive integers.
- We can perform a depth-first search (DFS) traversal of the tree to track the consecutive sequence length.
- We pass the current node, the expected value of the next node in the sequence, and the current length of the consecutive sequence.
- If the current node's value is equal to the expected value, we increase the current length by 1.
- We recursively check the left and right children with the updated expected value and length, and return the maximum length from both branches.
- At each node, we compare the current length with the global maximum length. :
class Solution {
int maxLen = 0;
public int longestConsecutive(TreeNode root) {
if (root == null) return 0;
dfs(root, root.val, 0);
return maxLen;
}
private void dfs(TreeNode node, int expected, int length) {
if (node == null) return;
if (node.val == expected) {
length++;
} else {
length = 1;
}
maxLen = Math.max(maxLen, length);
dfs(node.left, node.val + 1, length);
dfs(node.right, node.val + 1, length);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.