549. Binary Tree Longest Consecutive Sequence II
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the length of the longest consecutive sequence path in a binary tree. A path is consecutive if the values of adjacent nodes differ by exactly 1. The path can be increasing (e.g., [1, 2, 3]) or decreasing (e.g., [4, 3, 2]).
Solution
Binary Tree Longest Consecutive Sequence II in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def longestConsecutive(self, root: Optional[TreeNode]) -> int:
self.maxLength = 0
# Returns a tuple (inc_len, dec_len) for paths starting at `node` and going downwards.
def postorder(node: Optional[TreeNode]) -> tuple[int, int]:
if not node:
return 0, 0
# Get path lengths from children.
l_inc, l_dec = postorder(node.left)
r_inc, r_dec = postorder(node.right)
inc_from_left, dec_from_left = 0, 0
if node.left:
if node.left.val == node.val + 1:
inc_from_left = l_inc
if node.left.val == node.val - 1:
dec_from_left = l_dec
inc_from_right, dec_from_right = 0, 0
if node.right:
if node.right.val == node.val + 1:
inc_from_right = r_inc
if node.right.val == node.val - 1:
dec_from_right = r_dec
# Update maxLength with pivot paths that bend at the current node.
# Path: ... L(v-1) ... -> node(v) -> ... R(v+1) ...
self.maxLength = max(self.maxLength, dec_from_left + 1 + inc_from_right)
# Path: ... L(v+1) ... -> node(v) -> ... R(v-1) ...
self.maxLength = max(self.maxLength, inc_from_left + 1 + dec_from_right)
# Calculate lengths of downward paths starting at the current node.
my_inc = 1 + max(inc_from_left, inc_from_right)
my_dec = 1 + max(dec_from_left, dec_from_right)
# Update maxLength with these downward paths.
self.maxLength = max(self.maxLength, my_inc, my_dec)
# Return lengths for parent to use.
return my_inc, my_dec
postorder(root)
return self.maxLength
Binary Tree Longest Consecutive Sequence II in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int maxLength = 0;
public int longestConsecutive(TreeNode root) {
postorder(root);
return maxLength;
}
// Returns an array {inc_len, dec_len} for paths starting at `node` and going downwards.
private int[] postorder(TreeNode node) {
if (node == null) {
return new int[]{0, 0};
}
// Get path lengths from children.
int[] leftResult = postorder(node.left);
int l_inc = leftResult[0], l_dec = leftResult[1];
int[] rightResult = postorder(node.right);
int r_inc = rightResult[0], r_dec = rightResult[1];
int inc_from_left = 0, dec_from_left = 0;
if (node.left != null) {
if (node.left.val == node.val + 1) {
inc_from_left = l_inc;
}
if (node.left.val == node.val - 1) {
dec_from_left = l_dec;
}
}
int inc_from_right = 0, dec_from_right = 0;
if (node.right != null) {
if (node.right.val == node.val + 1) {
inc_from_right = r_inc;
}
if (node.right.val == node.val - 1) {
dec_from_right = r_dec;
}
}
// Update maxLength with pivot paths that bend at the current node.
// Path: ... L(v-1) ... -> node(v) -> ... R(v+1) ...
maxLength = Math.max(maxLength, dec_from_left + 1 + inc_from_right);
// Path: ... L(v+1) ... -> node(v) -> ... R(v-1) ...
maxLength = Math.max(maxLength, inc_from_left + 1 + dec_from_right);
// Calculate lengths of downward paths starting at the current node.
int my_inc = 1 + Math.max(inc_from_left, inc_from_right);
int my_dec = 1 + Math.max(dec_from_left, dec_from_right);
// Update maxLength with these downward paths.
maxLength = Math.max(maxLength, Math.max(my_inc, my_dec));
// Return lengths for parent to use.
return new int[]{my_inc, my_dec};
}
}
Binary Tree Longest Consecutive Sequence II in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int maxLength = 0;
public:
int longestConsecutive(TreeNode* root) {
postorder(root);
return maxLength;
}
private:
// Returns a pair {inc_len, dec_len} for paths starting at `node` and going downwards.
pair<int, int> postorder(TreeNode* node) {
if (!node) {
return {0, 0};
}
// Get path lengths from children.
auto [l_inc, l_dec] = postorder(node->left);
auto [r_inc, r_dec] = postorder(node->right);
int inc_from_left = 0, dec_from_left = 0;
if (node->left) {
if (node->left->val == node->val + 1) {
inc_from_left = l_inc;
}
if (node->left->val == node->val - 1) {
dec_from_left = l_dec;
}
}
int inc_from_right = 0, dec_from_right = 0;
if (node->right) {
if (node->right->val == node->val + 1) {
inc_from_right = r_inc;
}
if (node->right->val == node->val - 1) {
dec_from_right = r_dec;
}
}
// Update maxLength with pivot paths that bend at the current node.
// Path: ... L(v-1) ... -> node(v) -> ... R(v+1) ...
maxLength = max(maxLength, dec_from_left + 1 + inc_from_right);
// Path: ... L(v+1) ... -> node(v) -> ... R(v-1) ...
maxLength = max(maxLength, inc_from_left + 1 + dec_from_right);
// Calculate lengths of downward paths starting at the current node.
int my_inc = 1 + max(inc_from_left, inc_from_right);
int my_dec = 1 + max(dec_from_left, dec_from_right);
// Update maxLength with these downward paths.
maxLength = max({maxLength, my_inc, my_dec});
// Return lengths for parent to use.
return {my_inc, my_dec};
}
};
Binary Tree Longest Consecutive Sequence II in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function longestConsecutive(root: TreeNode | null): number {
let maxLength = 0;
// Returns a tuple [inc_len, dec_len] for paths starting at `node` and going downwards.
function postorder(node: TreeNode | null): [number, number] {
if (!node) {
return [0, 0];
}
// Get path lengths from children.
const [l_inc, l_dec] = postorder(node.left);
const [r_inc, r_dec] = postorder(node.right);
let inc_from_left = 0, dec_from_left = 0;
if (node.left) {
if (node.left.val === node.val + 1) {
inc_from_left = l_inc;
}
if (node.left.val === node.val - 1) {
dec_from_left = l_dec;
}
}
let inc_from_right = 0, dec_from_right = 0;
if (node.right) {
if (node.right.val === node.val + 1) {
inc_from_right = r_inc;
}
if (node.right.val === node.val - 1) {
dec_from_right = r_dec;
}
}
// Update maxLength with pivot paths that bend at the current node.
// Path: ... L(v-1) ... -> node(v) -> ... R(v+1) ...
maxLength = Math.max(maxLength, dec_from_left + 1 + inc_from_right);
// Path: ... L(v+1) ... -> node(v) -> ... R(v-1) ...
maxLength = Math.max(maxLength, inc_from_left + 1 + dec_from_right);
// Calculate lengths of downward paths starting at the current node.
const my_inc = 1 + Math.max(inc_from_left, inc_from_right);
const my_dec = 1 + Math.max(dec_from_left, dec_from_right);
// Update maxLength with these downward paths.
maxLength = Math.max(maxLength, my_inc, my_dec);
// Return lengths for parent to use.
return [my_inc, my_dec];
}
postorder(root);
return maxLength;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.