Leetcode Problem 298. Binary Tree Longest Consecutive Sequence

298. Binary Tree Longest Consecutive Sequence

Leetcode Solutions

Top Down Depth-first Search

  1. Initialize a global variable maxLength to 0.
  2. Define a recursive function dfs that takes a node p, its parent node parent, and the current length of the consecutive sequence.
  3. If the current node p is null, return immediately.
  4. If the current node p is consecutive with its parent (i.e., p.val == parent.val + 1), increment length; otherwise, reset length to 1.
  5. Update maxLength with the maximum of its current value and length.
  6. Recursively call dfs for the left and right children of p, passing the current node as the parent and the updated length.
  7. After the traversal, return maxLength as the result.
UML Thumbnail

Bottom Up Depth-first Search

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...