Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active September 2, 2017 20:11
Show Gist options
  • Save cixuuz/0bf4b051ae70b672422594c09e39921e to your computer and use it in GitHub Desktop.
Save cixuuz/0bf4b051ae70b672422594c09e39921e to your computer and use it in GitHub Desktop.
[538. Convert BST to Greater Tree] #leetcode
class Solution {
// O(n) o(1)
public TreeNode convertBST(TreeNode root) {
dfs(root, new int[1]);
return root;
}
private void dfs(TreeNode node, int[] sum) {
if (node == null) return;
dfs(node.right, sum);
sum[0] += node.val;
node.val = sum[0];
dfs(node.left, sum);
}
}
class Solution2 {
public TreeNode convertBST(TreeNode root) {
if (root == null) return null;
int sum = 0;
Deque<TreeNode> stack = new LinkedList<TreeNode>();
TreeNode cur = root;
while (!stack.isEmpty() || cur != null) {
if (cur != null) {
stack.add(cur);
cur = cur.right;
} else {
cur = stack.removeLast();
int tmp = cur.val;
cur.val += sum;
sum += tmp;
cur = cur.left;
}
}
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment