Created
April 7, 2018 18:14
-
-
Save shixiaoyu/a6bb17be1a60028b7ac0e9ce3a3d1f3b to your computer and use it in GitHub Desktop.
leetcode problem 538 https://leetcode.com/problems/convert-bst-to-greater-tree/description/
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
// 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