【tree 反转二叉树 inverse binary tree】

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        // bfs 
        if(root==null) return true;
        return isSymmetric(root.left, root.right);
    }
    private boolean isSymmetric(TreeNode left, TreeNode right){
        if(left==null&&right!=null) return false;
        if(right==null&&left!=null) return false;
        if(left==null&&right==null) return true;
        if(left.val==right.val){
            return isSymmetric(left.left, right.right)&&isSymmetric(left.right, right.left);
        }else{
            return false;
        }
    }
}

以上是迭代写法,镜面二叉树的形式

好,来一个递归写法:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        // bfs 
        if(root==null) return true;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        queue.add(root);
        while(queue.size()!=0){
            TreeNode cur1 = queue.poll();
            TreeNode cur2 = queue.poll();
            if(cur1==null&&cur2==null) continue;
            if(cur1==null) return false;
            if(cur2==null) return false;
            if(cur1.val==cur2.val){
                queue.add(cur1.left);
                queue.add(cur2.right);
                queue.add(cur1.right);
                queue.add(cur2.left);
            }else{
                return false;
            }
        }
        return true;
    }
    
}
点赞