/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int pre = 0;
TreeNode* convertBST(TreeNode* root) {
// 反中序遍历
if (!root) return nullptr;
convertBST(root->right);
pre += root->val;
root->val = pre;
convertBST(root->left);
return root;
}
};

该博客介绍了一种方法,通过反中序遍历将二叉搜索树转换为累加树,使得每个节点的值等于其所有祖先节点值的总和。在遍历过程中,使用`convertBST`函数更新节点值。
626

被折叠的 条评论
为什么被折叠?



