剑指offer:二叉树的镜像

题目描述

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

输入描述

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

解题思路

一、递归

如果root的左右子树都为空,返回false。否则使用一个临时节点交换每层的左右节点,再进入递归,依次处理root.leftroot.right

    public void Mirror(TreeNode root) {
            if(root == null) return; //根节点为空
            if(root.left == null && root.right == null) return; //左右子节点都为空,说明是叶子节点
            TreeNode node = root.left; 
            root.left = root.right;
            root.right = node;
            if(root.left != null){	//处理左子树
                Mirror(root.left);
            }
            if(root.right != null){	//处理右子树
                Mirror(root.right);
            }
        }

二、非递归

使用Stack,先处理root,将左右节点交换,再将左右节点入栈,下一轮循环处理,弹出右节点(交换之前的左节点),继续处理,等向左处理完所有节点,开始向右处理。整个过程类似先序遍历。

    public void Mirror(TreeNode root) {
            if(root == null) return;
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            //前序

            while(!stack.isEmpty()){
                //处理根节点,交换左右节点
                //下一轮循环处理root.left,等向左处理完开始向右处理。
                TreeNode node = stack.pop();
                TreeNode tmp = node.left;
                node.left = node.right;
                node.right = tmp;
                if(node.left != null){
                    stack.push(node.left); //左节点入栈
                }
                if(node.right != null){
                    stack.push(node.right); //右节点入栈
                }
            }
        }
posted @ 2020-03-07 17:07  灵图  阅读(103)  评论(0)    收藏  举报