Bloomberg Interview Question

Print out the k smallest element from a BST into a specified array, in the function form: firstKelement(treenode *root, int k, int *arr), without using any global variables.

Interview Answer

Anonymous

Jul 14, 2016

private static int[] printSmallestK(TreeNode root, int k, int[] a) { Stack<div>s = new Stack(); while(true) { if(root != null) { s.push(root); root = root.left; } else { if(s.isEmpty()) break; root = s.pop(); if(k > 0) { a[k-1] = root.key; k--; } root = root.right; } } return a; }</div>