Domanda di colloquio di Amazon

find the 2nd-largest node in a binary tree

Risposta di colloquio

Anonimo

15 dic 2011

a few solutions: 1) Using any of the traversal algorithms, keep track of max1 and max2 (max1 = maximum node in the tree). When you encounter a new node, you compare it with max1 first, and if the node is bigger you move max1 to max2. Or if it's smaller, compare it with max2 also. By the end you should have the maximum node in max1 and 2nd max in max2. Running time: O(n) 2) Traverse through and put everything into a binary search tree. Once you are done, find the farthest right node. That would be the largest node in the tree. If it has no children it's parent is the 2nd-largest. If it has children (left-node), then the max of the children is the 2nd-largest. 3) Traverse through and put everything into a max-heap. Call removeMax() twice to get the 2nd largest. I think all of these are O(n), but the first one should be the fastest.

2