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

Leetcode Problem 872. Leaf-Similar Trees

872. Leaf-Similar Trees

Leetcode Solutions

Depth First Search to Compare Leaf Sequences

  1. Define a helper function dfs that takes a node and a list as arguments.
  2. If the node is a leaf (no left or right child), append its value to the list.
  3. If the node has a left child, recursively call dfs on the left child.
  4. If the node has a right child, recursively call dfs on the right child.
  5. Call the dfs function on root1 and root2, each time with a new list to store leaf values.
  6. After the DFS traversal, compare the two lists of leaf values.
  7. If both lists are equal, return true; otherwise, return false.
UML Thumbnail

Iterative In-Order Traversal to Compare Leaf Sequences

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...