Description
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 the same value.
Example
Example 1:1
2
3
4
5
6
7Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:1
2
3
4
5
6
7Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:1
2
3
4
5
6
7Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
Solution
Solution 1: Recursion
Time Complex:
Space Complex:
1 | /** |
Solution 2: Iteration
Time Complex:
Space Complex:
1 | // Iteration solution, use stack to preorder trees |