Skip to content

Commit 12c415e

Browse files
authored
Create Recover Binary Search Tree.java
1 parent 1b21e54 commit 12c415e

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public void recoverTree(TreeNode root) {
18+
TreeNode nodeOne = null;
19+
TreeNode nodeTwo = null;
20+
TreeNode prevNode = null;
21+
Stack<TreeNode> stack = new Stack<>();
22+
while (root != null || !stack.isEmpty()) {
23+
while (root != null) {
24+
stack.push(root);
25+
root = root.left;
26+
}
27+
if (!stack.isEmpty()) {
28+
root = stack.pop();
29+
if (nodeOne == null && prevNode != null && prevNode.val > root.val) {
30+
nodeOne = prevNode;
31+
}
32+
if (nodeOne != null && prevNode.val > root.val) {
33+
nodeTwo = root;
34+
}
35+
prevNode = root;
36+
root = root.right;
37+
}
38+
}
39+
int tempValue = nodeOne.val;
40+
nodeOne.val = nodeTwo.val;
41+
nodeTwo.val = tempValue;
42+
}
43+
}

0 commit comments

Comments
 (0)