Compare Binary Trees at Matching Structural Positions

Quick Overview

Compare two binary trees for identical child structure and corresponding values, including null positions.

Compare Binary Trees at Matching Structural Positions

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Determine whether the binary trees rooted at `p` and `q` have exactly the same structure and the same value at every corresponding node. Left and right child positions are distinct: moving a node from one side to the other does not preserve the tree. The supplied `TreeNode` has `val`, `left`, and `right` fields: ```cpp bool isSameTree(TreeNode* p, TreeNode* q); ``` Examples use level-order displays with `null` for absent children; the arguments are tree pointers. ### Examples ```text Input: p = [4,2,6], q = [4,2,6] Output: true ``` ```text Input: p = [7,3], q = [7,null,3] Output: false ``` The second pair has the same visible values but different child positions. ### Constraints - Each tree has between 0 and 100 nodes. - Every node value is between -10000 and 10000, inclusive. - Compare both structure and values, including missing-child positions.

Overview: Compare two binary trees for identical child structure and corresponding values, including null positions.

Amazon logo
Amazon
Date not reported
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Determine whether the binary trees rooted at p and q have exactly the same structure and the same value at every corresponding node. Left and right child positions are distinct: moving a node from one side to the other does not preserve the tree.

The supplied TreeNode has val, left, and right fields:

bool isSameTree(TreeNode* p, TreeNode* q);

Examples use level-order displays with null for absent children; the arguments are tree pointers.

Examples

Input: p = [4,2,6], q = [4,2,6]
Output: true
Input: p = [7,3], q = [7,null,3]
Output: false

The second pair has the same visible values but different child positions.

Constraints

  • Each tree has between 0 and 100 nodes.
  • Every node value is between -10000 and 10000, inclusive.
  • Compare both structure and values, including missing-child positions.