Wednesday, November 4, 2015

[interview] Binary Search Tree operations

1. insert, simply recursion left and right until get to a node that without the direction node, then insert there.
2. delete node
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
BinaryTreenode delete(BinaryTreenode T, Comparable k) {
    if (T == null) return null;
    if (k.equals(T.val) {
       if (T. == null && T.getRight() == null) return null;
       if (T.left == null) return T.right();
       if (T.right() == null) return T.left();
      
       BinaryTreenode tmp = smallestNode(T.right());
       T.val = temp.val;

       T.right = delete(T.right, temp.val);
       return T;
    }
    else if (k.compareTo(T.getKey()) < 0) {
        T.left = delete(T.left, k) ;
       return T;
    }
    T.right = delete(T.right, k) );
    return T;
}

No comments:

Post a Comment