538. 把二叉搜索树转换为累加树
给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提醒一下,二叉搜索树满足下列约束条件:
节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。
解题思路
将二叉搜索树的中序遍历返回来便可以得到节点值的降序列
那么每个节点值降为它之前所有节点的值
记录节点值的累加赋予每个节点即可
运行结果
java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode convertBST(TreeNode root) {
build(root);
return root;
}
int sum=0;
public void build(TreeNode root){
if(root == null) return;
build(root.right);
sum+=root.val;
root.val=sum;
build(root.left);
}
}
京公网安备 11010502036488号