Created
April 26, 2018 15:42
-
-
Save s4553711/0e2a28c8bdcfce7c75789bc7a8798065 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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