bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 549. Binary Tree Longest Consecutive Sequence II

549. Binary Tree Longest Consecutive Sequence II

Leetcode Solutions

Single Traversal with Recursion

  1. Define a helper function longestPath(TreeNode node) that returns an array [inr, dcr].
  2. If the node is null, return [0, 0].
  3. Recursively call longestPath for the left and right children of the current node.
  4. If the left child's value is one less than the current node, update dcr as left_dcr + 1.
  5. If the left child's value is one more than the current node, update inr as left_inr + 1.
  6. Repeat steps 4 and 5 for the right child, taking the maximum values for inr and dcr.
  7. Update the global maximum path length as max(maxval, inr + dcr - 1).
  8. Return [inr, dcr] for the current node.
UML Thumbnail

Brute Force Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...
bugfree Icon
OR