Oracle Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
I guess, you can optimize this code to some extent.
The idea is if root element is less than key, then certainly all left child's element will have lesser value.
Pseudo Code:
printAll(node *root){
printAll(root->left);
printf("%d",root->data);
printAll(root->right);
}
print(node *root,int key){
if(root==null) return;
if(root->data <=key){
printAll(root->left);
printf("%d",root->data);
print(root->right,key);
}else{
print(root->left,key);
}
}
Not quite. If you're in a right subtree, everything above the subtree and to the left is smaller. So walking only the left child is incomplete.
o traverse to the key element
o if the element is a left-child(node->parent->left == node), then traverse the node->left subtree
o if the element is a right-child(node->parent->right == node), then traverse the node->parent->left subtree followed by node->parent followed by node->left subtree.
<will post working code soon>
The idea is simple. As you move right in the BST, in-order print the left subtree and the current node. As you move left in the subtree, print nothing since the search key is bigger than the current node key. If you find the key, print the left subtree and return.
I do a find() first so if the key doesn't exist, I simply return and print nothing. I guess that increases the running time by a constant factor and I'm sure it can be optimized.
def walkLeft(self, inputKey):
current = self._root
if self.find(inputKey) == None:
return
while current != None:
currentKey = current.getKey()
if inputKey == currentKey:
self.walkInOrder(current.getLeft())
return
elif inputKey > currentKey:
self.walkInOrder(current.getLeft())
print str(current.getKey()) + ',' + str(current.getData())
current = current.getRight()
else:
current = current.getLeft()
Here is a Java version:
public void printAllValuesSmallerThen(Node node, Integer value) {
if (node == null)
return;
this.printAllValuesSmallerThen(node.getLeftChild(), value);
if (node.getData() > value)
return;
else
System.out.print(node.getData() + " ");
this.printAllValuesSmallerThen(node.getRightChild(), value);
}
Do an inorder traversal, stopping when come to a larger key.
Possible pseudo-code
- Anonymous August 29, 2012