Same Tree

Easy#100tree nodes

You get the roots of two binary trees, p and q. Say whether they are the same tree: the same shape, with the same value in every matching place. Our trees: both are 5 with children 8 and 6; in p, 6 has a left child 4, in q, 6 has a right child 4 — the answer is false: the values are the same, but 4 sits on different sides.

input
p and q: two binary trees, each written as on LeetCode: its values level by level, left to right, null for a missing child.
returns
true if they are the same: the same shape and the same value in every node; otherwise false.
constraints
  • 0 ≤ the number of nodes in each tree ≤ 100
  • −10⁴ ≤ Node.val ≤ 10⁴
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
function isSameTree(p, q) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more depth-first search (dfs) problems

Pattern “Depth-first search (DFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.