Check if two binary trees are the same

Walk both trees together, node by node, confirming every structure and value lines up.

Time O(n)Space O(h)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Two trees are the same only if every position matches: both nodes are null, or both exist with equal values and equal left and right subtrees. Compare the two roots, and if they match, recursively compare their left children to each other and their right children to each other. A single mismatch anywhere, in either structure or value, makes the whole comparison false.

Code

public static bool IsSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) return true;
    if (p == null || q == null || p.val != q.val) return false;
    return IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);
}
static boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) return true;
    if (p == null || q == null || p.val != q.val) return false;
    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
bool isSameTree(TreeNode* p, TreeNode* q) {
    if (!p && !q) return true;
    if (!p || !q || p->val != q->val) return false;
    return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
def is_same_tree(p: TreeNode | None, q: TreeNode | None) -> bool:
    if p is None and q is None: return True
    if p is None or q is None or p.val != q.val: return False
    return is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)

Tips

In the .NET library

The same pairwise-recursion pattern (walk two trees together instead of one) also drives the mirror comparison in a symmetry check, with the right side compared against the left instead of itself.