剑指offer:二叉树镜像

题目描述

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

输入描述

二叉树的镜像定义:源二叉树

8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5

解题思路

  1. 递归版:遍历树的过程中不断进行子树交换
public class Solution {
public void Mirror(TreeNode root) {
if (root==null)
return;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
}
  1. 非递归版:由于不用考虑同级节点的交换顺序,所以栈和队列均可实现。

栈:

import java.util.*;
public class Solution {
public void Mirror(TreeNode root) {
if (root==null)
return;
Stack<TreeNode> contain = new Stack<TreeNode>();
contain.push(root);
while(!contain.empty()){
TreeNode node = contain.pop();
if(node.left!=null || node.right!=null){
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
if(node.left!=null)
contain.push(node.left);
if(node.right!=null)
contain.push(node.right);
}
}
}

队列:

import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public void Mirror(TreeNode root) {
if(root==null)return;
Queue<TreeNode> q=new LinkedList<TreeNode>();
q.add(root);
TreeNode t;
while(!q.isEmpty()){
t=q.poll();
if(t==null)continue;
TreeNode l=t.left;
TreeNode r=t.right;
t.left=r;
t.right=l;
q.add(r);
q.add(l);
}
}
}
posted @ 2018-01-11 08:34  小丑进场  阅读(141)  评论(0)    收藏  举报