Last active
September 2, 2017 20:11
-
-
Save cixuuz/0bf4b051ae70b672422594c09e39921e to your computer and use it in GitHub Desktop.
[538. Convert BST to Greater Tree] #leetcode
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
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