给定一个二叉搜索树,请将它的每个节点的值替换成树中大于或者等于该节点值的所有节点值之和。
如下图所示,帮助理解题目意思
- 节点0 对应的值为 0+1+2+3+4+5+6+7+8 = 36
- 节点1 对应的值为 1+2+3+4+5+6+7+8 = 36
- 节点2 对应的值为 2+3+4+5+6+7+8 = 35
- 节点3 对应的值为 3+4+5+6+7+8 = 33
- 节点4 对应的值为 4+5+6+7+8 = 30
- 节点5 对应的值为 5+6+7+8 = 26
- 节点6 对应的值为 6+7+8 = 21
- 节点7 对应的值为 7+8 = 15
- 节点8 对应的值为 8
代码实现
var convertBST = function (root) {
var res = 0;
f(root);
return root;
function f(node) {
if (node == null) return;
f(node.right);
res += node.val;
node.val = res;
f(node.left);
}
};