Bloomberg L.P. Interview Question: Print out the k smallest elem... | Glassdoor

Interview Question

Software Engineer Interview(Student Candidate)

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.
Answer

Interview Answer

1 Answer

0

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>

Anonymous on Jul 14, 2016

Add Answers or Comments

To comment on this, Sign In or Sign Up.