【发布时间】:2017-07-28 14:43:45
【问题描述】:
我必须找到二叉树的一个节点到它的根节点的距离。 我的解决方案是:
int distanceUtil(struct node* root, int x, int dist) {
if (root == NULL) {
return -1;
}
else {
if (root->data == x) {
return dist;
}
return distanceUtil(root->left, x, dist + 1) || distanceUtil(root->right, x, dist + 1);
}
}
int distance(struct node* root, int x) {
return distanceUtil(root, x, 0);
}
但它不起作用。事实上,我主要做的时候:
struct node* root = newNode(12);
root->left = newNode(8);
root->right = newNode(18);
root->left->left = newNode(2);
root->left->right = newNode(9);
root->right->left = newNode(15);
root->right->right = newNode(22);
root->right->right->right = newNode(33);
printf("il cammino : %d", distance(root,33));
getchar();
return 0;
它返回 1,但它应该返回 3。有人可以帮助我吗? 谢谢。
【问题讨论】:
-
||只返回 0 或 1。stackoverflow.com/a/18098119/3072566
标签: c data-structures tree binary-tree