BFS

Same Tree

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

Code:

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        // p and q are both null
        if (p == null && q == null) {
            return true;
        }
        // one of p and q is null (note here p and q can not be both null, because if so it is returned above)
        if (p == null || q == null) {
            return false;
        }
        // p and q are not null, check if they have the same value
        if (p.val != q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

Symmetric Tree

Link: https://leetcode.com/problems/symmetric-tree/

Code:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return isMirror(root, root);
    }
    
    boolean isMirror(TreeNode t1, TreeNode t2) {
        if (t1 == null & t2 == null) return true;
        if (t1 == null || t2 == null) return false;
        return (t1.val == t2.val)
            && isMirror(t1.left, t2.right)
            && isMirror(t1.right, t2.left);
    }   
}

Last updated