Sollicitatievraag bij Google

1. mutable, non mutable classes in Java 2. declaring constants in Java 3. x^y algorithm and its optimization. 4. second largest number from Binary Tree

Antwoorden op sollicitatievragen

Anoniem

10 sep 2012

For #4, is it possible the question was "how to find the second largest number in a Binary Search Tree"? If so, it can be done in O(log n) by starting at the root node, traversing right repeatedly until you reach a leaf node, and then returning the parent of that last node. If its just some random binary tree without any ordering, you'd have to traverse the whole tree.

5

Anoniem

10 sep 2012

For #4, is it possible the question was "how to find the second largest number in a Binary Search Tree"? If so, it can be done in O(log n) by starting at the root node, traversing right repeatedly until you reach a leaf node, and then returning the parent of that last node. If its just some random binary tree without any ordering, you'd have to traverse the whole tree.

3

Anoniem

10 sep 2012

Method1: Do a in order tree walk and return the last but one element. O(n) Method2: We can go the right sub-tree repeatedly until next is null. Then return the parent. O(logn)

2

Anoniem

27 okt 2012

For 3, There is an algorithm described here that can be done in O(n^1.59) time: http://www.cs.berkeley.edu/~vazirani/algorithms/chap2.pdf

Anoniem

15 mei 2013

public int findTreeSecLargest(Node root) { int count = 0; if (root != null) { // last right left return 1; // second return 2; count = 1 + findTreeSecLargest(root.right); } // second node of the last right node if (count == 2) { System.out.println("sec large " + root.x); } return count; }

Anoniem

21 okt 2012

Code for the last question in java with a recursive function: public static Integer getSecondLargest(Node root) { if (root == null) { return null; } Integer currentSecondLargest = null; if (root.myRight != null) { currentSecondLargest = root.myValue; Integer contenderFromRightSubTree = getSecondLargest(root.myRight); if (contenderFromRightSubTree != null) { currentSecondLargest = contenderFromRightSubTree; } } else if (root.myRight != null) { currentSecondLargest = root.myLeftmyValue; } return currentSecondLargest; }