FastPrepCheck Identical Binary Trees

Check Identical Binary Trees

Apple logoApple● EasyNEW GRADONSITE INTERVIEW
Learn

Problem statement

Return whether two binary trees are identical: they must have the same structure and the same value at every corresponding node. A missing left child must match a missing left child, and likewise for right children.

Do not modify either tree. Two empty trees are identical. Trees are displayed in level order with null for missing children.

Function

sameTree(first: TreeNode, second: TreeNode) → boolean

Examples

Example 1

first = [5,2,3,null,null,6]second = [5,2,3,null,null,6]return = true

Both trees have root five, left child two, right child three, and six as the left child of three, matching the source illustration.

Example 2

first = [1,2]second = [1,null,2]return = false

The value two occurs as a left child in one tree and a right child in the other.

Constraints

  • Each input is a valid binary tree with between 0 and 20000 nodes.
  • -10^9 <= node.val <= 10^9; values may repeat.

More Apple problems

See Apple hiring insights
public boolean sameTree(TreeNode first, TreeNode second) {
    // Write your solution here.
}
first[5,2,3,null,null,6]
second[5,2,3,null,null,6]
expectedtrue
Checking account…