从根到二叉树节点的距离

时间:2017-07-28 14:43:46

标签: c data-structures tree binary-tree

我必须从根节点找到二叉树节点的距离。 我的解决方案是:

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.有人可以帮助我吗? 感谢的。

2 个答案:

答案 0 :(得分:0)

您正在使用逻辑OR运算符||来组合搜索左侧树和右侧树的结果。运算符的结果总是0或1,所以除此之外你不会得到任何结果。

您真正想要的是返回每个子树搜索的两个值中较大的一个。因此,存储搜索每一侧的结果,然后检查哪一个更大并返回。

int distanceUtil(struct node* root, int x, int dist) {
    if (root == NULL) {
        return -1;
    }
    if (root->data == x) {
        return dist;
    }

    int left = distanceUtil(root->left, x, dist + 1);
    int right = distanceUtil(root->right, x, dist + 1);
    if (left > right) {
        return left;
    } else {
        return right;
    }
}

答案 1 :(得分:0)

int findDistance(Node *root,int key)
{
    if(root==NULL)
        return 1e9;
    if(root->data==key)
        return 0;
    return 1+min(findDistance(root->left,key),findDistance(root->right,key));
}
相关问题