題目描述:操作給定的二叉樹,将其變換為源二叉樹的鏡像。
二叉樹的鏡像定義:
源二叉樹
8
/ \
6 10
/ \ / \
5 7 9 11
鏡像二叉樹
8
/ \
10 6
/ \ / \
11 9 7 5
複制
題目描述
操作給定的二叉樹,将其變換為源二叉樹的鏡像。
二叉樹的鏡像定義:
源二叉樹
8
/ \
6 10
/ \ / \
5 7 9 11
鏡像二叉樹
8
/ \
10 6
/ \ / \
11 9 7 5
複制
解法 1: 遞歸
搞清楚鏡像的定義,簡單來說就是:從上到下,依次交換每個節點的左右節點。
來自《劍指 Offer》的示意圖:

代碼實作如下:
// ac位址:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/
// 原文位址:https://xxoo521.com/2020-01-13-tree-jing-xiang/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var mirrorTree = function(root) {
if (!root) {
return null;
}
// 交換目前節點的左右節點
const leftCopy = root.left;
root.left = root.right;
root.right = leftCopy;
// 對左右子樹做相同操作
mirrorTree(root.left);
mirrorTree(root.right);
return root;
};
複制