· 1 min read

Blind 75 - Same Tree

Placeholder

[Video]

Check if two trees have the same elements in the same positions.

Link

Approaches

O(n) time; O(1) space; 8 lines

This is a preferred solution.

I was originally trying the iterative approach, which was too complex.

Source: Java Solution better than 100% - LeetCode Discuss

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

Code optimization: null checks can become a single block

Optimized

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

Back to Blog