题目描述
给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提醒一下,二叉搜索树满足下列约束条件:
节点的左子树仅包含键 小于 节点键的节点。 节点的右子树仅包含键 大于 节点键的节点。 左右子树也必须是二叉搜索树。
示例 1:
输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
思路
- 明确我们是要处理每一个节点,对于二叉搜索树,我们通常的遍历方式事
中序遍历,但该题需要从最右边的节点开始处理,所以需要的遍历方式是:右中左 - 如何处理呢?——
双指针法
- pre=0;
- cur.val=pre+cur.val;
- pre=cur.val
代码
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
// 遍历顺序:右中左
function convertBST(root: TreeNode | null): TreeNode | null {
let pre=0
getResult(root,pre)
return root;
};
function getResult(root: TreeNode | null,pre:number): number| null{
// console.log(pre);
// 终止条件
if(root==null) return pre;
//右
pre= getResult(root.right,pre);
//中
root.val=root.val+pre;
pre=root.val;
// console.log(root.val,pre);
//左
pre=getResult(root.left,pre);
return pre;
}
总结
本题跟之前做过的二叉搜索树的题目类似,只是处理顺序是倒序。如有错误之处,欢迎大家留言指出,谢谢大家。