详细的问题是从给定节点找到距离为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回溯,但无济于事我无法给他留下深刻印象,无法编写代码。
关于在树上实现遍历的任何讨论对我都有帮助。
答案 0 :(得分:0)
最简单的方法是使用深度优先搜索,随时跟踪距离。它是一个简单的预订遍历,从"问题节点"开始。
void nodesAtDistance(struct node* qnode, int requestedDistance, int currentDistance)
{
if (qnode == null) return;
if (currentDistance == requestedDistance)
{
// output qnode
// and then return because children are further away
return;
}
// visit left and then right
nodesAtDistance(qnode->left, requestedDistance, currentDistance+1);
nodesAtDistance(qnode->right, requestedDistance, currentDistance+1);
}
所以如果你用:
来称呼它nodesAtDistance(myNode, 5, 0);
它将输出低于myNode
5级的所有节点。
现在,如果我将此作为API函数编写,我将提供一个不需要客户端传递currentDistance
参数的重载。因为如果有人写nodesAtDistance(myNode, 5, 1)
,你就会得到距离4的东西。所以,创造这个过载:
void nodesAtDistance(node * qnode, int requestedDistance)
{
nodesAtDistance(qnode, requestedDistance, 0);
}
将该功能公开显示,并将另一个功能设为私有。
答案 1 :(得分:0)
尝试此代码,虽然此代码仅检查子节点,但不会返回检查给定距离的祖先节点
#include<stdio.h>
#include<malloc.h>
struct treenode
{
unsigned int data;
struct treenode *left;
struct treenode *right;
};
struct treenode *treeptr, *sourcenode, *quesnode, *quesleftnode, *quesrightnode, *root = NULL;
struct node *treeptr insert_node(unsigned int treedata)
{
treeptr= (struct node*)(malloc(sizeof(treenode)));
treeptr->data = nodevalue;
treeptr->left = NULL;
treeptr->right = NULL;
return treeptr;
}
printnodesdistancek(struct treenode* quesnode, unsigned char reqdist)
{
unsigned char curdist=0;
do
{
if(quesnode == null)
return;
quesleftnode = quesnode->left;
if(curdist == reqdist)
{
printf("%d",quesleftnode->data);
}
else
{
quesnode= quesnode->left;
}
quesrightnode = quesnode->right;
if(curdist == reqdist)
{
printf("%d",quesrightnode->data);
}
else
{
quesnode = quesnode->right;
}
}while(quesnode!=NULL);
//main function
void main(void)
{
//create tree
*root = insert_node(1);
root->left=insert_node(-1);
root->right=insert_node(2);
root->left->left=insert_node(-2);
root->left->right=insert_node(3);
root->right->left=insert_node(-3);
root->right->right=insert_node(4);
sourcenode = root->left;
printnodesdistancek(sourcenode,1);
}