二叉樹的鏡像
題目描述:
操作給定的二叉樹,將其變換爲源二叉樹的鏡像。
輸入描述:
二叉樹的鏡像定義:源二叉樹
8
/ \
6 10
/ \ / \
5 7 9 11
鏡像二叉樹
8
/ \
10 6
/ \ / \
11 9 7 5
問題分析:
將左右子節點調換,利用遞歸走完所有的節點
代碼展示:
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function Mirror(root)
{
// 交換左右子樹的節點,遞歸調用該方法完成遍歷
if(root === null)
return;
let tmp = root.left; //交換節點
root.left = root.right;
root.right = tmp;
Mirror(root.left); //遞歸左兒子
Mirror(root.right); //遞歸右兒子
}