Before attempting this problem, you should be comfortable with:
The brute force approach considers every possible path in the tree and checks if it forms a consecutive sequence. For each node, we explore all paths passing through it by examining every possible starting and ending point in its subtrees.
Where is the number of nodes in the input tree
We can find the longest consecutive path in a single traversal by tracking two values at each node: the length of the longest increasing path going down and the length of the longest decreasing path going down. A node can potentially be the turning point where an increasing path from one subtree meets a decreasing path from the other, forming a complete consecutive sequence. By combining these two lengths at each node, we find the longest path passing through that node.
[increasing length, decreasing length] starting from the current node.null, return [0, 0].1 (just the current node).1), extend the appropriate length.(increasing + decreasing - 1), since the current node is counted twice.[increasing, decreasing] for the parent to use.class Solution:
def longestConsecutive(self, root: TreeNode) -> int:
def longest_path(root: TreeNode) -> List[int]:
nonlocal maxval
if not root:
return [0, 0]
inr = dcr = 1
if root.left:
left = longest_path(root.left)
if (root.val == root.left.val + 1):
dcr = left[1] + 1
elif (root.val == root.left.val - 1):
inr = left[0] + 1
if root.right:
right = longest_path(root.right)
if (root.val == root.right.val + 1):
dcr = max(dcr, right[1] + 1)
elif (root.val == root.right.val - 1):
inr = max(inr, right[0] + 1)
maxval = max(maxval, dcr + inr - 1)
return [inr, dcr]
maxval = 0
longest_path(root)
return maxvalWhere is the number of nodes in the input tree
A node with value parent.val + 1 extends the increasing path from the child's perspective, but it is tracked as dcr (decreasing from root down). The naming can be confusing. Ensure you correctly match which direction each variable tracks.
# If child.val = parent.val - 1, parent extends child's increasing path
# If child.val = parent.val + 1, parent extends child's decreasing pathWhen combining increasing and decreasing paths through a node, that node is counted in both. The formula is inr + dcr - 1, not inr + dcr.
# Wrong: maxval = max(maxval, inr + dcr)
# Correct: maxval = max(maxval, dcr + inr - 1)Both left and right children can contribute to either increasing or decreasing paths. You must take the maximum from both children for each direction, not assume left contributes to one and right to the other.