Posts Recover Binary Search Tree
Post
Cancel

Recover Binary Search Tree

PROBLEM DESCRIPTION

Two elements of a binary search tree (BST), represented by root A are swapped by mistake. Tell us the 2 values swapping which the tree will be restored.
interviewbit

SOLUTION

snapshot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Pair{
    int x;
    int y;
    Pair(int x, int y){
        this.x = x;
        this.y = y;
    }
} 

public class Solution {

    public ArrayList<Integer> recoverTree(TreeNode A) {

        ArrayList<Pair> list = new ArrayList<>();

        ArrayList<Integer> inorder = new ArrayList<>();
        inorder(A, inorder);

        if(inorder.size() <= 1) return null;

        for(int i=1; i<inorder.size(); i++){
            if(inorder.get(i) < inorder.get(i-1)){
                Pair p = new Pair(inorder.get(i-1), inorder.get(i));
                list.add(p);
            }
        }

        ArrayList<Integer> ans = new ArrayList<>();

        if(list.size() == 1){
            ans.add(list.get(0).y);
            ans.add(list.get(0).x);
            return ans;
        }

        ans.add(list.get(1).y);
        ans.add(list.get(0).x);

        return ans;

    }

    public void inorder(TreeNode root, List<Integer> list){
        if(root == null) return;
        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }
}
This post is licensed under CC BY 4.0 by the author.