You get the roots of two binary trees, p and q. They are the same when they have the same shape and the same value in every node: each node of one tree has a node with the same value in the same place in the other. Return whether they are the same.
Example: two trees, each with 5 at the root, 3 and 8 under it, and 1 and 4 under 3, are the same. If the second tree has no 4 under its 3, they are not.
Try it yourself first: LeetCode 100 ↗. Then step through the solution below.
Write each tree out as a list, in preorder, with a mark for every empty child, and compare the two lists. That is linear time, O(n + m) for trees of n and m nodes, but it builds both lists in full and reads both trees to the end, even when their roots already differ. Leave out the marks, and two different shapes can give the same list.
The clue is in the words "the same value in the same place". Two trees are the same when their roots hold the same value, their left subtrees are the same, and their right subtrees are the same. Each subtree pair is the same problem on smaller trees.
So a call compares one pair of nodes. Two empty nodes are the same; one empty node against a node is not; two nodes with different values are not. Otherwise the answer is the two calls on the children, joined by and: a no from the left children ends it without comparing the right ones.
The player runs the code on the example. Press → for each step: the lines it runs light up in the code.
On a phone, Full screen keeps the picture and the code on one screen.
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def is_same_tree(p, q): if p is None and q is None: return True if p is None or q is None: return False if p.val != q.val: return False return (is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right))
Now write it yourself on LeetCode 100 ↗, or go on: Lowest Common Ancestor of a Binary Search Tree →
p and q. They are the same if they have one shape with the same value in each place. Are they?p and q are the two 3s, and the call on 5 and 5 waits. Both are nodes and both hold 3: on to their children.p and q are the two 1s, leaves: both are nodes and both hold 1, so on to their children.p and q are the left children of 1 and 1, both empty (∅): two empty trees are the same, so this call returns yes.p and q are the right children of 1 and 1, also empty (∅): this call returns yes too.p and q are the two 4s, leaves: both are nodes and both hold 4, so on to their children.p and q are the left children of 4 and 4, both empty (∅): two empty trees are the same, so this call returns yes.p and q are the right children of 4 and 4, also empty (∅): this call returns yes too.p and q are the two 8s, leaves: both are nodes and both hold 8, so on to their children.p and q are the left children of 8 and 8, both empty (∅): two empty trees are the same, so this call returns yes.p and q are the right children of 8 and 8, also empty (∅): this call returns yes too.Note
In Java and C++ the return is written with &&, which stops at the first false just as Python's and does: when the left children differ, the right ones are never compared.
| Approach | Time | Space |
|---|---|---|
| Brute force: write both trees out with empty marks, compare | O(n + m) | O(n + m) |
| A queue of node pairs instead of recursion | O(n) | O(w) |
| Compare the roots, then both pairs of children, recursively this page | O(n) | O(h) |
n and m are the numbers of nodes in the two trees, n the smaller; h and w are the smaller tree's height and the number of nodes on its widest level.
Note
One call compares one pair, so the calls nest as deep as the two trees share a path. Python allows 1,000 nested calls by default: two chains of about a thousand nodes raise RecursionError, even when they are equal. In Java and C++ no number is set: the thread's stack size decides. The queue of pairs in the follow-up has no such limit.
The same code on trees that differ in one place: 3 has a right child, 4, in the first tree and none in the second. Up to step 11 it runs as before; at step 12 the trees part. Press → for each step.
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def is_same_tree(p, q): if p is None and q is None: return True if p is None or q is None: return False if p.val != q.val: return False return (is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right))
p and q are the two 3s, and the call on 5 and 5 waits. Both are nodes and both hold 3: on to their children.p and q are the two 1s, leaves: both are nodes and both hold 1, so on to their children.p and q are the left children of 1 and 1, both empty (∅): two empty trees are the same, so this call returns yes.p and q are the right children of 1 and 1, also empty (∅): this call returns yes too.p is 4 and q is empty (∅): one tree has a node where the other has none. This call returns no.The blocks below are steps of Same Tree in words, and two of them do not belong. A block that compares two children “the same way” runs your lines again, from line 1, on that pair of children. Put the right ones in order and check: your algorithm runs on the example and on the two trees of the walkthrough "When the answer is no", so a mistake shows in its answer. Once it is right, the code appears beside your blocks.
Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. Two of them don't belong.
Your algorithm
To compare the trees under p and q:
Blocks
Now write it yourself on LeetCode 100 ↗, or go on: Lowest Common Ancestor of a Binary Search Tree →
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def is_same_tree(p, q): if p is None and q is None: return True if p is None or q is None: return False if p.val != q.val: return False return (is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right))Can you compare the two trees without recursion? Yes, with a queue of pairs: put in the two roots, and each time take a pair out. Two empty nodes match, so go on to the next pair; one empty node, or two different values, answer no at once; otherwise put in the pair of left children and the pair of right children. When the queue runs empty, the answer is yes. The same O(n) time, and a very deep tree cannot hit the recursion limit.
What if the second tree may sit anywhere inside the first? That is Subtree of Another Tree (LeetCode 572): run this comparison from every node of the big tree, O(m · n) for trees of m and n nodes. Writing both trees out with empty marks and a separator before every value, so that 2 is not found inside 12, and searching one string in the other with a linear-time search, such as KMP, brings it down to O(m + n).
LeetCode is a trademark of LeetCode LLC. VisiGrab is not affiliated with LeetCode or with Blind; the problems are told in our own words, with our own examples.