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:

Last updated