一、Problem
Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.
Input: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Constraints:
The number of nodes in the tree is between 1 and 100.
Each node will have value between 0 and 100.
The given tree is a binary search tree.
二、Solution
方法一:dfs
如果要你求所有小於當前結點的值的和等於當前結點的新值,那麼你很容易想到中序遍歷,反過來求這道題也是一樣的:
- 右路突到盡頭,然後返回,讓當前結點加上右子樹的總和,並記錄當前結點的總和 pre
- 左路突破,沒到達一個結點就加上 pre,繼續向左深入
class Solution {
int pre;
void dfs(TreeNode root) {
if (root == null)
return;
dfs(root.right);
root.val += pre;
pre = root.val;
dfs(root.left);
}
public TreeNode bstToGst(TreeNode root) {
dfs(root);
return root;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,