美文网首页
剑指offer(十八)二叉树的镜像

剑指offer(十八)二叉树的镜像

作者: 向前的zz | 来源:发表于2020-04-06 08:19 被阅读0次

点击进入 牛客网题库:二叉树的镜像

方法一

借用辅助空间

 public void Mirror(TreeNode root) {
        if(root == null) {
            return;
        }

        ArrayList<TreeNode> list = new ArrayList<>();
        list.add(root);
        while(!list.isEmpty()) {
            TreeNode node = list.remove(0);
            TreeNode tmpNode = node.left;
            node.left = node.right;
            node.right = node.left;

            if(node.left!=null) {
                list.add(node.left);
            }

            if(node.right!=null) {
                list.add(node.right);
            }
        } 
    }
}

方法二

public class Solution {
    public void Mirror(TreeNode root) {

        if(root == null) {
            return;
        }
        TreeNode tmpNode = root.left;
        root.left = root.right;
        root.right = tmpNode;

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

相关文章

网友评论

      本文标题:剑指offer(十八)二叉树的镜像

      本文链接:https://www.haomeiwen.com/subject/tefvphtx.html