Same Tree
EasyTrees
Given the roots of two binary trees, p and q, return True if they are the same tree and False otherwise.
Two trees are the same when they have exactly the same shape and every pair of nodes in matching positions holds the same value. Two empty trees are the same.
Trees are written in level order: values are listed level by level, left to right, and null marks a missing child (trailing nulls are omitted).
Example 1
- Input:
- p = [1,null,2], q = [1,2]
- Output:
- False
- Explanation
- Both trees hold the values 1 and 2, but one hangs the 2 on the right and the other on the left, so the shapes differ.
Example 2
- Input:
- p = [4,2,6,1,3], q = [4,2,6,1,3]
- Output:
- True
- Explanation
- Every node in
phas a node with the same value in the same position inq, and neither tree has extra nodes.
Example 3
- Input:
- p = [4,2,6], q = [4,6,2]
- Output:
- False
- Explanation
- The shapes match and the roots match, but the left children are 2 and 6, so the trees are different.
Constraints
- The number of nodes in each tree is in the range
[0, 100] -10^4 <= Node.val <= 10^4