- 請完成一個函數,輸入一個二叉樹,該函數輸出它的鏡像。
- 例如輸入:
4
/ \
2 7
/ \ / \
1 3 6 9
- 鏡像輸出:
4
/ \
7 2
/ \ / \
9 6 3 1
- 來源:力扣(LeetCode)
- 鏈接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof
- 著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
思路
需要獲得樹的鏡像,只需要將節點的左右節點互換即可
這邊直接使用遞歸,替換即可
實現
public TreeNode mirrorTree(TreeNode root) {
if (root == null) {
return null;
}
if (root.left != null || root.right != null) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
mirrorTree(root.right);
mirrorTree(root.left);
return root;
}
如果當前節點為null,遞歸借宿
只要該節點有左葉子節點或者右葉子節點,即需要交換葉子節點的位置
最后遞歸處理左右子節點