# 递归的一个问题？

codinghuang
• 142

``````/**
* 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* convertBST(TreeNode* root) {
static int sum = 0;
if (root == NULL) {
return root;
}

convertBST(root->right);
root->val += sum;
sum = root->val;
convertBST(root->left);

return root;
}
};``````

``````/**
* 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* convertBST(TreeNode* root) {
int sum = 0;
convert(root, sum);

return root;
}

void convert(TreeNode* root, int &sum) {

if (root == NULL) {
return ;
}

convert(root->right, sum);
root->val += sum;
sum = root->val;
convert(root->left, sum);
}
};``````

1 个回答
✓ 已被采纳

2 / 212 test cases passed.

5 2 13
2 1 3

[25,26,23]

``````...
Solution　*s;
s->convertBST(root1);
s->convertBST(root2);``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进