1.栈+中序遍历
每个节点的值都是加上中序遍历比自己大的节点的值,使用栈存在中序遍历的结果,然后遍历栈,更改节点的值
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* bstToGst(TreeNode* root) {
//二叉搜索树的中序遍历是升序,每个节点加上中序遍历其后的节点的值,用栈存储中序遍历
if(root==NULL)
return root;
stack<TreeNode*> s;
inOrder(root,s);
int sum=0;
while(!s.empty())
{
TreeNode *node=s.top();
node->val+=sum;
sum=node->val;
s.pop();
}
return root;
}
void inOrder(TreeNode *root,stack<TreeNode*> &s)
{
if(root==NULL)
return ;
inOrder(root->left,s);
s.push(root);
inOrder(root->right,s);
}
};
2.递归
思想和上述方法一样,只是不再借助栈
就是反向中序遍历
代码如下:
class Solution {
public:
int presum=0;
TreeNode* bstToGst(TreeNode* root) {
if(root==NULL)
return root;
bstToGst(root->right);
root->val+=presum;
presum=root->val;
bstToGst(root->left);
return root;
}