题目描述:
给出二叉搜索树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提醒一下,二叉搜索树满足下列约束条件:
节点的左子树仅包含键小于节点键的节点。
节点的右子树仅包含键大于节点键的节点。
左右子树也必须是二叉搜索树。
比较简单的深度遍历,然后赋值就好,注意的是这里的tem是全局变量
代码:
class Solution {
int tem = 0;
public TreeNode bstToGst(TreeNode root) {
dfs(root);
return root;
}
public void dfs (TreeNode root){
if(root.right != null){
dfs(root.right);
}
tem = tem + root.val;
root.val = tem;
if(root.left != null){
dfs(root.left);
}
}
}