博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CareerCup Randomly return a node in a binary tree
阅读量:4184 次
发布时间:2019-05-26

本文共 1484 字,大约阅读时间需要 4 分钟。

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.

转载地址:http://cwboi.baihongyu.com/

你可能感兴趣的文章
Git配置用户信息
查看>>
删除Linux用户
查看>>
Python list pop方法:弹出列表内的元素
查看>>
Python调用C程序
查看>>
Go标识符
查看>>
Git移动文件,重命名文件
查看>>
Go errors.New函数:创建错误对象
查看>>
Go操作符和分隔符
查看>>
Linux rmdir命令:删除空目录
查看>>
制作Python3的docker镜像
查看>>
Python 字符串方法总结
查看>>
MySQL in Action(持续更新中...)
查看>>
Go make函数:创建slice,map和channel
查看>>
Go字面量(字面常量)
查看>>
Git修改文件权限
查看>>
Mac Homebrew安装的MySQL无法远程登录问题解决
查看>>
Linux tree命令:显示目录结构
查看>>
Go append函数:给切片添加元素/合并切片
查看>>
Go os.Stdin:指向标准输入文件的指针
查看>>
Python list index方法:查询具有特定值的元素的索引
查看>>