Randomly return a node in a binary tree, program in C/C++, and define the class or struct of the binary tree by yourself.
---------------------------------------------------------------------------
This question can be solved by using just one traverse of the binary tree.
The idea is, do a whatever order of travel, if it is the kth node we are traveling, then replace the previously selected node with probability 1/k.
/*******************************************************************************************************/
Similar Problem & other answers:
Suppose we use binary search tree to implement set, design an algorithm that we can get an random element from the set, while maintain
all the other set operations have same complexities.
--------------------------------------------------------------------------
Here is my thought: all we need is an API which will find the kth element in the tree, such as tree.find(int k). For the kth element, we can achieve O(n) time complexity using normal binary search tree itself.
If we want better, we can store some
counts of child elements in the node, and so the delete and insert operation would need to update the count of all its Ancestors. The final performance of search would depend on the snap shot of tree at the time. If it is more like balanced binary search tree,
you got the O(log(n)). If it is more like a list, it is O(n). But it will all guarantee the uniform probability distribution at any snapshot of the tree.

本文提供了一种方法,在二叉树中通过一次遍历来随机返回一个节点,并自行定义二叉树的类或结构。重点介绍了通过特定概率替换已选节点的方法。
1285

被折叠的 条评论
为什么被折叠?



