剑指offer 27:二叉树的镜像

题目描述:

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

数据范围:二叉树的节点数0≤n≤1000 , 二叉树每个节点的值0≤val≤1000

要求: 空间复杂度 O(n)。本题也有原地操作,即空间复杂度 O(1) 的解法,时间复杂度 O(n)O(n)

比如:

源二叉树

镜像二叉树

 

示例1

输入:{8,6,10,5,7,9,11}

返回值:{8,10,6,11,9,7,5}

说明:如题面所示

示例2

输入:{}

返回值:{}

解法一:递归

思路:

1、处理根节点,如果根节点为空,或者根节点左右子树违抗,则直接返回。否则对左右节点进行交换。

2、处理根节点的左子树,再处理根节点的右子树

代码:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    public TreeNode Mirror (TreeNode pRoot) {
        // write code here
        if(pRoot == null){
            return null;
        }
        if(pRoot.left == null && pRoot.right == null){
            return pRoot;
        }
        //交换节点
        TreeNode temp = pRoot.left;
        pRoot.left = pRoot.right;
        pRoot.right = temp;
        //左右子树分别进行镜像翻转
        Mirror(pRoot.left);Mirror(pRoot.right);
        return pRoot;
        
    }
}

解法二:辅助栈/队列

思路:

1、当 pRoot为空时,直接返回 null。
2、初始化: 栈(或队列),用栈stack 加入根节点 pRoot。
3、循环交换: 当栈 stack 为空时跳出。
      (1)出栈: 记为 node ;
      (2)添加子节点: 将 node 左和右子节点入栈;
      (3)交换: 交换 node 的左 / 右子节点。
4、返回值: 返回根节点 pRoot 。

如下图:

代码:

import java.util.*;
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    public TreeNode Mirror (TreeNode pRoot) {
        // write code here
        if(pRoot == null) return null;
        // 构建辅助栈
        Stack<TreeNode> stack = new Stack<>();
        // 根节点入栈
        stack.add(pRoot);
        while(!stack.isEmpty()) {
            // 节点出栈
            TreeNode node = stack.pop();
            // 根节点的左右子树入栈
            if(node.left != null) stack.add(node.left);
            if(node.right != null) stack.add(node.right);
            // 左右子树交换
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return pRoot;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值