Boomerang Commerce Interview Question
Developer Program EngineersCountry: India
Interview Type: In-Person
We just want the left view, so what we can do is keep an array to hold the nodes we encounter in a traversal. We will traverse the right side before the left, ultimately overwriting nodes that are right-most with ones that are left most.
void printLeftSide(Node head) {
Node[] left = new Node[getTreeHeight(head)];
traverse(head, 0, left);
print(left.toString);
}
void traverse(Node curr, int depth, Node[] arr) {
if (curr == null) { return; }
traverse(curr.right, depth+1, arr);
arr[depth] = curr;
traverse(curr.left, depth+1, arr);
}
int getTreeHeight(Node head) {
if (head == null) { return 0; }
return Max(getTreeHeight(head.left), getTreeHeight(head.right)) + 1;
}
left view of a binary tree is the nodes which will be visible when tree is visited from left side. Its basically the first node (or leftmost node) at each level of the tree
Output 12 10 25
- aayush2k11 February 08, 2015