avatar

二叉树的镜像

题目描述

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

输入描述

二叉树的镜像定义:源二叉树 
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5

思路

第一种思路

镜像的意思就是说将左右子树进行换位,所以直接递归就解决了。

代码

第一种思路


import java.util.LinkedList;
import java.util.Queue;

public class Main {
public static void main(String[] args) {
TreeNode root1 = new TreeNode(8);
TreeNode treeNode1 = new TreeNode(8);
TreeNode treeNode2 = new TreeNode(7);
TreeNode treeNode3 = new TreeNode(9);
TreeNode treeNode4 = new TreeNode(2);
TreeNode treeNode5 = new TreeNode(4);
TreeNode treeNode6 = new TreeNode(7);
root1.left =treeNode1;
root1.right = treeNode2;
treeNode1.left = treeNode3;
treeNode1.right = treeNode4;
treeNode4.left = treeNode5;
treeNode4.right = treeNode6;
Squeue(root1);
Mirror(root1);
System.out.println("之后");
Squeue(root1);
}
public static void Mirror(TreeNode root) {
if(root==null) return;
else
{
TreeNode left = root.left;
TreeNode right = root.right;
root.right = left;
root.left = right;
Mirror(root.left);
Mirror(root.right);
}
}
private static void Squeue(TreeNode root)
{
if(root!=null)
{
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty())
{
root = q.poll();
System.out.print(root.val+" ");
if(root.left!=null)
{
q.offer(root.left);
}
if(root.right!=null)
{
q.offer(root.right);
}
}
}
}
}
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}
}
文章作者: zenshin
文章链接: https://zlh.giserhub.com/2020/03/13/ckbbo2j4c002jpkwafse03kus/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 zenshin's blog
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论