Citigroup Interview Question
AnalystsCountry: United States
Assuming that question is about binary search tree, because there can't be a fixed strategy to add an element in a normal binary tree.
Basic Java implementation (wwithout delete operation):
public class BST {
private class Node {
private int value;
private Node left;
private Node right;
public Node(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
private Node root; // root of BST
public void insert(int item) {
root = insert(root, item);
}
private Node insert(Node x, int item) {
if (x == null) {
return new Node(item);
}
if (item < x.value) {
x.left = insert(x.left, item);
} else if (item > x.value) {
x.right = insert(x.right, item);
}
return x;
}
public void inOrder() {
inOrder(root);
System.out.println();
}
private void inOrder(Node x) {
if (x == null) {
return;
}
inOrder(x.left);
System.out.print(x.value + " ");
inOrder(x.right);
}
public static void main(String[] args) {
BST t = new BST();
t.insert(5);
t.insert(2);
t.insert(1);
t.insert(3);
t.insert(6);
t.insert(7);
t.insert(4);
t.inOrder();
}
}
//tree implementation
- Nik March 27, 2012