package demo;
import java.util.Stack;
/*
* 题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
*/
public class Offer_38 {
public void Mirror(TreeNode root) {
//所谓镜像,就是左右子树交换位置
if(root == null)
return;//若为空则直接返回
Stack<TreeNode> stack = new Stack<TreeNode>();//新建一个栈空间
stack.push(root);//将给定树入栈
while(!stack.empty()) {//若栈不为空
TreeNode node = stack.pop();//将出栈数据保存在新建的node中
if(node.left != null || node.right != null) {//若node左右均不为空
TreeNode nodeLeft = node.left;//新建左右TreeNode节点
TreeNode nodeRight = node.right;
node.left = nodeRight;//交换左右节点
node.right = nodeLeft;
}
if(node.left != null)//若左右节点不为空则入栈
stack.push(node.left);
if(node.right != null)
stack.push(node.right);
}
}
public static void main(String[] args) {
Offer_38 off = new Offer_38();
TreeNode root = new TreeNode(1);
root.left = new TreeNode(6);
root.right = new TreeNode(10);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(7);
root.right.left = new TreeNode(9);
root.right.right = new TreeNode(11);
}
}
二叉树的镜像
最新推荐文章于 2021-03-26 21:02:56 发布