题目地址:
https://www.lintcode.com/problem/convert-bst-to-greater-tree/description
给定一个BST,要求将每个节点的值改为大于等于该值的所有叶子节点值之和。
由于对于一棵BST而言,其中序遍历是单调递增的,所以我们的思路是,对这个二叉树做右中左的中序遍历,同时用一个全局变量记录比当前节点更大的值的和,不停累加并赋值即可。代码如下:
public class Solution {
private int sum = 0;
/**
* @param root: the root of binary tree
* @return: the new root
*/
public TreeNode convertBST(TreeNode root) {
// write your code here
dfs(root);
return root;
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.right);
// 先将比当前节点值更大的节点和加到当前节点上去
root.val += sum;
// 接着更新sum为当前节点值,这样遍历到下一个节点的时候就可以继续累加上去
sum = root.val;
dfs(root.left);
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。