gpt4 book ai didi

计算一个节点是否在 BST 中有任何子节点

转载 作者:行者123 更新时间:2023-12-05 01:06:59 26 4
gpt4 key购买 nike

我有一个问题,我知道如何像这样计算树中的所有节点 return 1 + rightchild(tree->right) + rightchild(tree->left); 现在我的问题是如果一个节点在该节点中有任何子节点,我将如何计算,图像来展示我正在尝试做的事情。

image

static int rightchild(const treeNode* tree){

if(tree == NULL){
return 0;
}

if(tree->right !=NULL){
return 1 + rightchild(tree->right) + rightchild(tree->left);
}
else {
return rightchild(tree->left);
}

}

static int leftchild(const treeNode* tree){

if(tree == NULL){
return 0;
}

if(tree->left != NULL){
return 1 + leftchild(tree->right) + leftchild(tree->left);
}
else {
return leftchild(tree->right);
}

}

希望我走在正确的道路上,我只是遗漏了一些我将两个函数的结果结合起来的东西,但它总是不准确。

最佳答案

您应该计算当前节点中的子节点数,并将子节点的子节点数加到其中。

static int countchild(const treeNode* tree) {
int childrenNum = 0;
if (tree == NULL) {
return 0;
}
if (tree->left != NULL) {
/* this node has a child in left + add the number of children in the left subtree */
childrenNum += 1 + countchild(tree->left);
}
if (tree->right != NULL) {
/* this node has a child in right + add the number of children in the right subtree */
childrenNum += 1 + countchild(tree->right);
}
return childrenNum;
}

关于计算一个节点是否在 BST 中有任何子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68042649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com