Same Tree

Pattern: Depth, diameter and balance

easy

Two trees are the same when both are empty, or both roots have the same value and their left subtrees are the same and their right subtrees are the same.

The problem

Return whether two binary trees have the same shape and the same values. [1, 2, 3] and [1, 2, 3] are the same; [1, 2] and [1, null, 2] are not. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • When are two empty trees the same?
  • What if exactly one is empty?
  • What must hold for two non-empty trees?

Hints

    Brute force, and why it fails

    Serialise both with null markers and compare the strings: also O(n), more memory.

    The key insight

    Sameness is defined recursively, so checking roots and recursing is the whole algorithm.

    Dry run

    rootsequal

    p = [1, 2, 3], q = [1, 2, 3]. Roots 1 and 1 match.

    Step 1 of 3

    The plan

    same(p, q): if p or q is null: return p == q
                return p.val == q.val and same(p.left, q.left) and same(p.right, q.right)
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each pair of nodes is compared once.

    Edge cases

    • Both empty: true.
    • One empty: false.
    • Same values, different shape: false.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if (p == null || q == null) return p == q;  // both empty, or one missing
            return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        }
    }

    C++

    class Solution {
    public:
        bool isSameTree(TreeNode* p, TreeNode* q) {
            if (p == NULL || q == NULL) return p == q;  // both empty, or one missing
            return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
        }
    };

    Python

    class Solution:
        def isSameTree(self, p, q) -> bool:
            if not p or not q:
                return p is q                       # both empty, or one missing
            return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

    Common mistakes

    • Comparing only the values in some traversal order.
    • Forgetting the case where one side is null.

    Similar problems