(TreeNode root)
| 13 | // } |
| 14 | |
| 15 | public TreeNode convertBST(TreeNode root) { |
| 16 | int sum = 0; |
| 17 | TreeNode node = root; |
| 18 | Stack<TreeNode> stack = new Stack<TreeNode>(); |
| 19 | |
| 20 | while (!stack.isEmpty() || node != null) { |
| 21 | /* push all nodes up to (and including) this subtree's maximum on |
| 22 | * the stack. */ |
| 23 | while (node != null) { |
| 24 | stack.add(node); |
| 25 | node = node.right; |
| 26 | } |
| 27 | |
| 28 | node = stack.pop(); |
| 29 | sum += node.val; |
| 30 | node.val = sum; |
| 31 | |
| 32 | /* all nodes with values between the current and its parent lie in |
| 33 | * the left subtree. */ |
| 34 | node = node.left; |
| 35 | } |
| 36 | |
| 37 | return root; |
| 38 | } |
| 39 | } |