Two classic questions that turn out to be the same algorithm, so they share one lesson:
p and q of two binary trees, return true if they are identical: the same shape and the same value at every position.root of one binary tree, return true if it is a mirror of itself around its centre.Same Tree: p = [1, 2, 3], q = [1, 2, 3] -> true
p = [1, 2], q = [1, null, 2] -> false (same values, different shape)
Symmetric Tree: root = [1, 2, 2, 3, 4, 4, 3] -> true
root = [1, 2, 2, null, 3, null, 3] -> falseHere's the connection. To check two trees are the same, compare them position by position: the roots, then left with left and right with right. A tree is symmetric when its left subtree is the mirror of its right subtree — the same comparison, except the pairs are crossed: left with right, and right with left.
Free account
Sign up to read the rest of this lesson: 6 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come