题目:
翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
备注:
这个问题是受到 Max Howell 的 原问题 启发的 :
谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
解决:
/*
* @lc app=leetcode.cn id=226 lang=javascript
*
* [226] 翻转二叉树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
const inverse = (invertRoot) => {
if (!invertRoot) {
return;
}
exchange(invertRoot);
inverse(invertRoot.left);
inverse(invertRoot.right);
}
const exchange = (exchangeRoot) => {
let temp;
temp = exchangeRoot.left;
exchangeRoot.left = exchangeRoot.right;
exchangeRoot.right = temp;
}
inverse(root);
return root;
};
// @lc code=end
注: 仔细看就是先把最底下的节点反转,然后上一个节点再翻转。例如:1 - 3 反转成 3 - 1,6 - 9 反转成 9 - 6, 然后再让 2 - 7 反转。当然反过来也一样,先反转 2 - 7 也是可以的。