/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
//遞歸函數的終止條件
if(root==null) return null;
//下面三句是將當前節點的左右子樹交換
TreeNode tmpnode=root.left;
root.left = root.right;
root.right=tmpnode;
//遞歸交換當前節點的 左子樹
mirrorTree(root.left);
//遞歸交換當前節點的 右子樹
mirrorTree(root.right);
return root;
}
}
參考博客鏈接: