Binary Tree EqualLoading saved progress…

Binary Tree Equal

Implement binaryTreeEqual(a, b) that returns whether two binary trees are the same tree: identical in shape AND carrying the same value at every corresponding node. This is the classic LeetCode "Same Tree" problem. Each node is a plain object { val, left, right }, and an absent child or an empty tree is null.

Signature

// A binary tree node, or null for an absent child / empty tree.
//   type Node = { val: unknown; left: Node | null; right: Node | null };
//
// a: Node | null  — the first tree's root.
// b: Node | null  — the second tree's root.
// returns: boolean — true only if both trees have the SAME shape AND the
//                    SAME value at every matching position.
function binaryTreeEqual(a, b): boolean;

Examples

// Identical three-node trees → true.
const a = { val: 1, left: { val: 2, left: null, right: null }, right: { val: 3, left: null, right: null } };
const b = { val: 1, left: { val: 2, left: null, right: null }, right: { val: 3, left: null, right: null } };
binaryTreeEqual(a, b); // → true
// Same values, mirrored placement (2 on the left vs. on the right) → false.
const a = { val: 1, left: { val: 2, left: null, right: null }, right: null };
const b = { val: 1, left: null, right: { val: 2, left: null, right: null } };
binaryTreeEqual(a, b); // → false

Notes

  • Both empty is equal. binaryTreeEqual(null, null) returns true — two missing trees match.
  • Shape counts, not just values. Trees with the same set of values but different structure (a child on the left in one, on the right in the other) are not equal.
  • One present, one absent means false. If a position holds a node in one tree and null in the other, the trees differ right there.
  • Compare values with ===. Treat node values as primitives compared by strict equality; you do not need to handle objects-as-values.
  • Don't mutate the inputs. You only read val, left, and right.
Loading editor…