Algo-Sim › Binary Trees & BST

Same Tree

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Two trees are the same when their roots match and their left and right subtrees are the same: recurse on both trees in step.

Problem

Given the roots of two binary trees p and q, return true if they are the same: identical in shape, with equal values in matching positions. Two empty trees are the same.

Constraints

Edge cases to test

Follow-up questions

How do you compare without recursion?
Walk both trees with one queue of node pairs.
How do you check many trees for duplicates?
Serialise each subtree to a string or id and count them in a hash map (LC 652): O(n) with ids.

Solution

Java

public boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) return true;
    if (p == null || q == null) return false;
    if (p.val != q.val) return false;
    return isSameTree(p.left, q.left)
        && isSameTree(p.right, q.right);
}

Python

def is_same_tree(p, q):
    if not p and not q:
        return True
    if not p or not q:
        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))

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        if (p == nullptr && q == nullptr)
            return true;
        if (p == nullptr || q == nullptr)
            return false;
        if (p->val != q->val)
            return false;
        return isSameTree(p->left, q->left)
               && isSameTree(p->right, q->right);
    }
};

More Binary Trees & BST problems