1. 本題知識點
二叉樹
2. 題目描述
操作給定的二叉樹,將其變換爲源二叉樹的鏡像。
源二叉樹:
8
/ \
6 10
/ \ / \
5 7 9 11
鏡像二叉樹:
8
/ \
10 6
/ \ / \
11 9 7 5
3. 解題思路
- 如果當前結點爲空,直接返回
- 交換當前結點的左右子樹
- 遞歸左右子樹
4. 代碼
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
/**
* 操作給定的二叉樹,將其變換爲源二叉樹的鏡像。
* @param root
*/
public void Mirror(TreeNode root) {
// 如果當前結點爲空,直接返回
if (root == null) {
return;
}
// 交換當前結點的左右子樹
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
// 遞歸左右子樹
Mirror(root.left);
Mirror(root.right);
}
}