101. Symmetric Tree

101. Symmetric Tree

判断树是不是自身镜像对称

My Solutions:

class Solution {
    public boolean isSymmetric(TreeNode root) {
    
    //recursive - bottom up 
//         return isMirror(root, root);
//     }
    
//     public boolean isMirror(TreeNode n1, TreeNode n2) {
//         if (n1 == null && n2 == null) return true;
//         if (n1 == null || n2 == null) return false;
//         return n1.val == n2.val && isMirror(n1.left, n2.right) && isMirror(n1.right, n2.left);
        
        //iterative
        Queue<TreeNode> q = new LinkedList<>();
        
        q.add(root);
        q.add(root);
        while (!q.isEmpty()) {
            TreeNode n1 = q.poll();
            TreeNode n2 = q.poll();
            
            if (n1 == null && n2 == null) continue;
            if (n1 == null || n2 == null) return false;
            if (n1.val != n2.val) return false;
            q.add(n1.left); // 注意这里,因为是镜像对称,所以要把两个互为镜像的一组加进去
            q.add(n2.right);
            q.add(n1.right);
            q.add(n2.left);
        }
        return true;
    }
}

Last updated