問題描述:
操作給定的二叉樹,將其變換爲源二叉樹的鏡像。 二叉樹結點定義爲:
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
例如:
8 / \ 6 10 / \ / \ 5 7 9 11 鏡像二叉樹 8 / \ 10 6 / \ / \ 11 9 7 5
思路:
從根結點出發,遞歸的,首先交換左右子樹,然後將變化後的左右子樹變換爲其鏡像。
代碼:
public void Mirror(TreeNode root) {
if(root == null){
return;
}
if(root.left == null && root.right == null){
return;
}
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if(root.left != null){//這裏加入判空條件可以及時終止遞歸,會少進行一次遞歸,減少棧存儲的壓力
Mirror(root.left);
}
if(root.right != null){
Mirror(root.right);
}
}