Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created April 7, 2018 18:14
Show Gist options
  • Save shixiaoyu/a6bb17be1a60028b7ac0e9ce3a3d1f3b to your computer and use it in GitHub Desktop.
Save shixiaoyu/a6bb17be1a60028b7ac0e9ce3a3d1f3b to your computer and use it in GitHub Desktop.
// Below is the online solution that keeps a running sum, no extra space is needed other than recursion stack
private int accumulatingSum = 0;
public TreeNode convertBST(TreeNode root) {
// Reset the accumulating sum
this.accumulatingSum = 0;
this.reverseInorderTraversal(root);
return root;
}
public void reverseInorderTraversal(TreeNode node) {
if (node == null) {
return;
}
this.reverseInorderTraversal(node.right);
this.accumulatingSum += node.val;
node.val = this.accumulatingSum;
this.reverseInorderTraversal(node.left);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment