剑指 offer 面试题 27 二叉树的镜像(递归,栈)

二叉树的镜像

个人博客

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:

4
/
2 7
/ \ /
1 3 6 9

镜像输出:

4
/
7 2
/ \ /
9 6 3 1

题解
  • 递归

    • 思路
      • 最终要的是找到二叉树镜像的规律
      • 画图可以看出二叉树的镜像就是递归地交换二叉树的左右节点
    • 复杂度分析
      • 时间复杂度 O(n)
      • 空间复杂度 O(n):最差的情况下(当二叉树退化为链表)需要使用 O(n)大小的栈空间
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode mirrorTree(TreeNode root) {
            if(root == null)return null;
            TreeNode temp = root.left;
            root.left = mirrorTree(root.right);
            root.right = mirrorTree(temp);
            return root;
        }
    }
    

    Jw09Qb

  • 辅助队列(栈)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode mirrorTree(TreeNode root) {
            if(root == null)return null;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            while(queue.size() != 0){
                TreeNode outStack = queue.poll();
                TreeNode temp = outStack.right;
                if(outStack.left != null)queue.add(outStack.left);
                if(outStack.right != null)queue.add(outStack.right);
                outStack.right = outStack.left;
                outStack.left = temp;
            }
            return root;
        }
    }
    

    SBJPmt

总结
  • 多画图,找规律
  • 可以分解为交换左右子节点的问题,找到子问题自然找到递归的写法了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值