gpt4 book ai didi

c++ - 获取二叉搜索树中的节点数

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:11:14 26 4
gpt4 key购买 nike

所以我正在研究一种获取二叉搜索树中节点数的方法,当我有 3 个节点时,它会给我 3 个,但如果我做 5 个,它会给我 4 个,我需要更改什么?

int BinaryTree::size(int count, Node *leaf) const
{
if(leaf != NULL)//if we are not at a leaf
{
size(count + 1, leaf->getLeft());//recurisvly call the function and increment the count
size(count + 1, leaf->getRight());
}
else
{
return count;//return the count
}

}

最佳答案

int BinaryTree::size(Node *leaf) const 
{
if(leaf == NULL) { //This node doesn't exist. Therefore there are no nodes in this 'subtree'
return 0;
} else { //Add the size of the left and right trees, then add 1 (which is the current node)
return size(leaf->getLeft()) + size(leaf->getRight()) + 1;
}
}

虽然这是一种不同的方法,但我发现它比您的方法更容易阅读。

关于c++ - 获取二叉搜索树中的节点数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15372979/

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