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);
}
}
}
}
操作给定的二叉树,将其变换为源二叉树的镜像。
最新推荐文章于 2020-07-09 01:54:32 发布