100. Same Tree
Reference: LeetCode
Difficulty: Easy
Problem
Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are
structurally identical
and the nodes have thesame value
.
Example:
1 | // 1 |
Analysis
Recursion
Note: Do the null check
at the beginning.
1 | public boolean isSameTree(TreeNode p, TreeNode q) { |
Time: $O(N)$
Space: $O(h)$
Iteration
Use two stacks to simulate the preorder traversal.
Note:
Stack
andQueue
can containnull
elements, whileDeque
can’t.- Do
null check
first, and then do thevalue check
. Make surep
andq
are notnull
. - The
while condition
should consider two stacks at the same time. - The
return
statement should check if two stacks are empty at the same time.
1 | public boolean isSameTree(TreeNode p, TreeNode q) { |
Time: $O(N)$
Space: $O(h)$
Comment