代码随想录:把二叉搜索树转化为累加树
相当于将数组从右到左遍历,下一个数加上一个数,二叉搜索树中序遍历(左中右)为顺序,右中左则为倒叙
/**
* 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:
TreeNode* pre = NULL;
TreeNode* bstToGst(TreeNode* root) {
if (root == NULL)
return root;
if (root->right)
root->right = bstToGst(root->right);
if (pre != NULL)
root->val += pre->val;
pre = root;
if (root->left)
root->left = bstToGst(root->left);
return root;
}
};

浙公网安备 33010602011771号