相当于将数组从右到左遍历,下一个数加上一个数,二叉搜索树中序遍历(左中右)为顺序,右中左则为倒叙
/**
* 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;
}
};
标签:pre,right,TreeNode,val,随想录,累加,二叉,root,left
From: https://www.cnblogs.com/huigugu/p/18680457