100. Same Tree

https://leetcode.com/problems/same-tree/

O(n)

O(n)

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }
        // means (p == null && q != null) || (p != null && q == null)
        // so if (p == null && q == null) { should put first
        // then we can just write p == null || q == null here
        if (p == null || q == null) { 
            return false;
        }
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

Last updated