【牛客网-名企高频面试题】 NC72 二叉树的镜像

【牛客网-名企高频面试题】 NC72 二叉树的镜像

题目描述:

操作给定的二叉树,将其变换为源二叉树的镜像。
在这里插入图片描述
递归版本:

public void Mirror_1(TreeNode root) {
        if(root == null){
            return;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        Mirror(root.left);
        Mirror(root.right);
    }

非递归版本:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.*;
public class Solution {
    
    //利用二叉树的广度优先搜索实现镜像
    public void Mirror(TreeNode root) {
        if(root == null)
            return;
        Queue<TreeNode> nodes = new LinkedList<>();
        TreeNode curr,temp;
        nodes.offer(root);
        while(!nodes.isEmpty()){
            int len = nodes.size();
            for(int i= 0;i< len;i++){
                curr = nodes.poll();
                temp = curr.left;
                curr.left = curr.right;
                curr.right = temp;
                if(curr.left != null)
                    nodes.offer(curr.left);
                if(curr.right != null)
                    nodes.offer(curr.right);
            }
        }
    }
}
posted @ 2021-01-12 22:10  your_棒棒糖  阅读(29)  评论(0)    收藏  举报