Check whether two binary trees are the same
Coding problemEasyAsked in: Amazon, Flipkart, Microsoft
Given the roots of two binary trees, first and second, 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 matching nodes holds the same value.
Trees are written in level order, with null for a missing child. Two empty trees are the same.
Examples
Example 1
Input: first = [1,2,3], second = [1,2,3]
Output: true
Example 2
Input: first = [1,2], second = [1,null,2]
Output: false
Same values, but 2 is a left child in one tree and a right child in the other.
Example 3
Input: first = [1,2,1], second = [1,1,2]
Output: false
Constraints
- Each tree has between 0 and 100,000 nodes
- Each value is a 32-bit integer
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.