You are on page 1of 8

Recover Binary Search Tree

Recover Binary Search Tree


You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were
swapped by mistake. Recover the tree without changing its structure
Recover Binary Search Tree
Input:
root = [1,3,null,null,2]
Output:
[3,1,null,null,2]
Explanation:
3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.
1 class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode() {}
6 TreeNode(int val) {
7 this.val = val;
8 }
9 TreeNode(int val, TreeNode left, TreeNode right) {
10 this.val = val;
11 this.left = left;
12 this.right = right;
13 }
14 }
15
16
17
18
19
20
21
22
23 class Solution {
24 public void recoverTree(TreeNode root) {
25 Stack<TreeNode> stack = new Stack<>();
26 TreeNode current = root;
27 TreeNode lastProcessed = null;
28 TreeNode[] swapped = new TreeNode[2];
29 while (!stack.isEmpty() || current != null) {
30 while (current != null) {
31 stack.push(current);
32 current = current.left;
33 }
34 current = stack.pop();
35 if (lastProcessed != null && lastProcessed.val > current.val) {
36 if (swapped[0] == null) {
37 swapped[0] = lastProcessed;
38 swapped[1] = current;
39 }
40 else {
41 swapped[1] = current;
42 break;
43 }
44 }
45 lastProcessed = current;
46 current = current.right;
47 }
48 int temp = swapped[0].val;
49 swapped[0].val = swapped[1].val;
50 swapped[1].val = temp;
51 }
52 static void printInorder(TreeNode node)
53 {
54 if (node == null)
55 return;
56 printInorder(node.left);
57 System.out.print(" " + node.val);
58 printInorder(node.right);
59 }
60 }
61
62
63
64
65
66
THANK YOU

You might also like