- 請(qǐng)完成一個(gè)函數(shù),輸入一個(gè)二叉樹,該函數(shù)輸出它的鏡像。
- 例如輸入:
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
- 著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
思路
需要獲得樹的鏡像,只需要將節(jié)點(diǎn)的左右節(jié)點(diǎn)互換即可
這邊直接使用遞歸,替換即可
實(shí)現(xiàn)
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;
}
如果當(dāng)前節(jié)點(diǎn)為null,遞歸借宿
只要該節(jié)點(diǎn)有左葉子節(jié)點(diǎn)或者右葉子節(jié)點(diǎn),即需要交換葉子節(jié)點(diǎn)的位置
最后遞歸處理左右子節(jié)點(diǎn)