二叉树的镜像

题目大意

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述

image.png

分析

遍历二叉树,当前结点有左节点或者右节点的时候,交换左右节点。然后可以递归的翻转左子树和右子树。

代码一:递归

public void Mirror(TreeNode root) {
        if(root == null || (root.left == null && root.right == null)) return;
         //交换左右孩子
         TreeNode temp = root.left;
         root.left = root.right;
         root.right = temp;
         Mirror(root.left);
         Mirror(root.right);
    }

代码二:利用栈

利用栈进行树的先序遍历,消除递归。

public void Mirror(TreeNode root) {
        if(root == null) return;
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while(!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            if(cur.left!=null)
                stack.push(cur.left);
            if(cur.right!=null)
                stack.push(cur.right);
            if(cur!=null && (cur.left!=null || cur.right !=null)) {
                TreeNode temp = cur.left;
                cur.left = cur.right;
                cur.right = temp;
            }
        }
    }

总结

题目比较简单,只需要搞清楚,翻转的条件——至少有一个孩子。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容