劍指 Offer 27. 二叉樹的映象(簡單)
阿新 • • 發佈:2021-08-16
通過率79.0%
題目描述:
請完成一個函式,輸入一個二叉樹,該函式輸出它的映象。
例如輸入:
4
/ \
2 7
/ \ / \
1 3 6 9
映象輸出:
4
/ \
7 2
/ \ / \
9 6 3 1
示例 1:
輸入:root = [4,2,7,1,3,6,9]
輸出:[4,7,2,9,6,3,1]
限制:
0 <= 節點個數 <= 1000
思路:
遞迴交換每個節點的左右子樹
1 /*JavaScript*/ 2 /** 3 * Definition for a binary tree node. 4 * function TreeNode(val) {5 * this.val = val; 6 * this.left = this.right = null; 7 * } 8 */ 9 /** 10 * @param {TreeNode} root 11 * @return {TreeNode} 12 */ 13 var mirrorTree = function(root) { 14 if(root) { 15 const temp = root.left 16 root.left = mirrorTree(root.right) 17 root.right = mirrorTree(temp)18 } 19 return root 20 };