二叉树的镜像

题目描述

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

输入描述

输入

解题思路

  • 采用递归解决此题即可,不断交换根节点下的左右结点,再以左右结点分别为根节点做交换。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

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

}

}
*/
public class Solution {
public void Mirror(TreeNode root) {
if(root == null){
return;
}
exchange(root);
Mirror(root.left);
Mirror(root.right);
}

private TreeNode exchange(TreeNode root){
TreeNode a = root.left;
root.left = root.right;
root.right = a;
return root;
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!
Powered By Valine
v1.5.2