【发布时间】:2020-11-07 07:04:49
【问题描述】:
如何翻转二叉树?我最近遇到了这个问题,我所有的尝试都失败了。初始树如下所示。
4
/ \
2 7
/ \ / \
1 3 6 9
4
/ \
7 2
/ \ / \
9 6 3 1
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var invertTree = function(root) {
};
【问题讨论】:
-
[root.left, root.right] = [root.right, root.left]然后为孩子做同样的事情 -
只需将左节点与右节点交换,试试我的二叉树类,它带有构建它的函数 reverse()。参考链接 - 类 - npmjs.com/package/@dsinjs/binary-tree 文档 - dsinjs.github.io/binary-tree/#reverse
标签: javascript algorithm tree binary