轻车熟路

二叉树的镜像

http://www.nowcoder.com/questionTerminal/564f4c26aa584921bc75623e48ca3011

思路一:递归
1、求左子树镜像
2、求右子树镜像
3、求自身镜像

public class Solution {
    /**
    *1、先求左子树的镜像
    *2、求右子树的镜像
    *3、求自身的镜像
    **/
    public void Mirror(TreeNode root) {
        if(root==null){
            return;
        }

        Mirror(root.left);
        Mirror(root.right);

        if(root.left!=null||root.right!=null){
            TreeNode temp = root.left;
            root.left=root.right;
            root.right=temp;
        }
        return;

    }
}

思路二:广度优先遍历

public class Solution {
    //广度优先遍历bfs
    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);
            }
        }

    }
}
全部评论

相关推荐

Java面试先知:我也是和你一样的情况,hr 说等开奖就行了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务