Leaf-Similar Trees

The leaf value sequence of a binary tree is the list of its leaf values read from left to right. Given the roots of two binary trees, return true if their leaf value sequences are the same, and false otherwise.

30:00

Leaf-Similar Trees
easy
Free written solution
Topics
Companies

The leaf value sequence of a binary tree is the list of its leaf values read from left to right. Given the roots of two binary trees, return true if their leaf value sequences are the same, and false otherwise.

Example 1:
Input: {"root1":[3,5,1,6,2,9,8,null,null,7,4],"root2":[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]}
Output: true
Constraints:
  • The number of nodes in each tree is in the range [1,200][1, 200].

  • Both trees have values in the range [0,200][0, 200].

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root1":[3,5,1,6,2,9,8,null,null,7,4],"root2":[3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]}

Walk tree 1 with a stack, starting from its root 3. Popping left before right visits leaves from left to right.

root1

351629874

root2

351674298

leaves1

leaves2

stack (top first)

3
popped node
on stack
leaf, numbered in order
matched
mismatch
Variables
VariableValue
treeroot1
nodenull
stack[3]
leaves1[]
leaves2[]
DepthFunction Call
Stack empty
0/35