您的位置:首页 > 其它

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

2017-10-25 20:03 309 查看
package com.dixin.temp;

import java.util.LinkedList;

/**
* Created by admin on 2017/10/25.
* 操作给定的二叉树,将其变换为源二叉树的镜像。
*/
public class J {
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;

}
}
// @1 递归实现
public void Mirror(TreeNode root) {
if(root==null) {
return;
}
TreeNode tmp=root.left;//当前节点的左节点和右节点交换
root.left=root.right;
root.right=tmp;
Mirror(root.left);
Mirror(root.right);
}
//@2 队列实现
public void Mirror2(TreeNode root) {
LinkedList<TreeNode> queue=new LinkedList<>();
if(root==null) {
return;
}
queue.add(root);//将二叉树加到队列中
while (!queue.isEmpty()) {
TreeNode node=queue.poll();
TreeNode tmp=node.left;
node.left=node.right;
node.right=tmp;
if(node.left!=null) {//左子树不为空将其放入队列中
queue.add(node.left);
}
if(node.right!=null) {//右子树不为空将其放入队列中
queue.add(node.right);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: