I'm trying to solve the following problem:
at first we have a bst with root 0 and nothing else. not we add n given numbers like a which:
not for instance we start to add n = 7 numbers to the tree:
19 3 5 25 21 -4 2
after adding all the numbers,the goal is to find the parent of each node in the order they were added:
0 19 3 19 25 0 3
My first approach was to build the tree while adding the nodes and print the parent at the same time:
private static TreeNode treeInsert(TreeNode root, TreeNode newNode) {
TreeNode y = null;
TreeNode x = root;
while (x != null) {
y = x;
if (newNode.key < x.key) x = x.left;
else x = x.right;
}
newNode.parent = y;
if (y == null) root = newNode;
else if (newNode.key < y.key) y.left = newNode;
else y.right = newNode;
return newNode;
}
and this auxiliary class:
class TreeNode {
TreeNode left;
TreeNode right;
TreeNode parent;
int key;
public TreeNode(int key) {
this.key = key;
}
so I can find the parent.The problem here is this algorithm is to slow! if the given numbers are too many and if we consider the tree is unbalanced then it might take forever to add new nodes. The time limit on this problem is 1 and because of the reasons I mentioned I'm exceeding that limit. I cant balance the tree because the the parents change. But maybe there is a way to solve the problem without constructing a bst and just focusing on finding the parents using the numbers.
Thank you.