Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created April 26, 2018 15:42
Show Gist options
  • Save s4553711/0e2a28c8bdcfce7c75789bc7a8798065 to your computer and use it in GitHub Desktop.
Save s4553711/0e2a28c8bdcfce7c75789bc7a8798065 to your computer and use it in GitHub Desktop.
/**
* 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) {
if (root) {
int sum = 0;
dfs(root, sum);
}
return root;
}
void dfs(TreeNode* root, int &sum) {
if (root->right) {
dfs(root->right, sum);
}
int tmp = root->val;
root->val += sum;
sum += tmp;
if (root->left) dfs(root->left, sum);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment