【发布时间】:2014-03-22 19:34:20
【问题描述】:
详细的问题是找到与给定节点的距离为 x(即边数 =x)的所有节点。
今天在亚马逊面试中被问到,
void findNodeWithDistanceX(struct node* root,struct node * qnode, int value)
{
//root is root Node, qnode is questionnode from which distance to be calculated, value is the
//distance to be calculated
//finding distance between root and qnode
int distance = findDistancefromRoot(root ,qnode);
if(distance> value)
{
traverseDistancedown(root ,distance-value);
}
if(distance ==value){
printf("%d",root->value);
}
// Traverse and find all nodes with distance value from 'qnode' down the tree
traverseDistancedown(qnode,value);
现在如果从 qnode 找到距离“值”。
我没有得到答案如何遍历树并满足距离与值的条件。
虽然这里出现了很多情况。
我尝试从 qnode 回溯,但无济于事,我无法打动他,也无法编写代码。
任何关于实现向上遍历树的讨论都会对我有所帮助。
【问题讨论】:
-
广度优先搜索?
-
对了,请格式化你的代码...希望这不是你在采访中展示的版本
标签: algorithm data-structures tree binary-search-tree