121 - 538 把二叉树转换为累加树
Last updated
Was this helpful?
Last updated
Was this helpful?
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:
输入: 二叉搜索树: 5 / 2 13
输出: 转换为累加树: 18 / 20 13
只能想到,先变成数组,然后一个个做判断加上去。。
这人用上了二叉树的定义,一下子就简洁了很多。从右往左深度优先遍历,遍历过的都加上就完事了。因为左边总是小于右边的。
这个人的图:
Runtime: 84 ms, faster than 78.13% of JavaScript online submissions for Convert BST to Greater Tree.
Memory Usage: 40.2 MB, less than 25.00% of JavaScript online submissions for Convert BST to Greater Tree.
Runtime: 84 ms, faster than 59.94% of Python3 online submissions for Convert BST to Greater Tree.
Memory Usage: 16.3 MB, less than 6.25% of Python3 online submissions for Convert BST to Greater Tree.
Runtime: 188 ms, faster than 88.55% of Go online submissions for Convert BST to Greater Tree.
Memory Usage: 283.6 MB, less than 100.00% of Go online submissions for Convert BST to Greater Tree.
go好像不能像js和python一样,函数里面套函数,只能拆在外面。
就不能是直接的深度遍历,而是要从最右节点开始遍历,因此要加一个字段。。
Runtime: 88 ms, faster than 34.49% of Python3 online submissions for Convert BST to Greater Tree.
Memory Usage: 16.4 MB, less than 6.25% of Python3 online submissions for Convert BST to Greater Tree.
Runtime: 92 ms, faster than 40.63% of JavaScript online submissions for Convert BST to Greater Tree.
Memory Usage: 42.6 MB, less than 25.00% of JavaScript online submissions for Convert BST to Greater Tree.
好像用obj改成key-value这样的结构更好。。但遍历就变得很麻烦,还要用keys和delete来维护。。