題目描述
輸入描述:
二叉樹的鏡像定義:源二叉樹 8 / \ 6 10 / \ / \ 5 7 9 11 鏡像二叉樹 8 / \ 10 6 / \ / \ 11 9 7 5
其實就是交換二叉樹的左右子樹,可用遞歸實現:
交換根節點的左右子樹,再分別對左子樹進行鏡像和右子樹進行鏡像
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class jingzi {
public void Mirror(TreeNode root) {
if(root == null){
return;
}else{
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
Mirror(root.left);
Mirror(root.right);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(4);
root.left = new TreeNode(5);
root.right = new TreeNode(6);
jingzi jj = new jingzi();
jj.Mirror(root);
}
}