C++ 一种计算二叉树中奇数正元素数的函数
我有作业,我不知道如何在二叉树中递归计算奇数 我试过for语句,但我的老师说我需要递归,这将是很容易做到的,但我不能得到它C++ 一种计算二叉树中奇数正元素数的函数,c++,count,tree,binary,C++,Count,Tree,Binary,我有作业,我不知道如何在二叉树中递归计算奇数 我试过for语句,但我的老师说我需要递归,这将是很容易做到的,但我不能得到它 // create Tree struct Node { int key; Node *left, *right; }; // Function to print all odd nodes void oddNode(Node* root) { if
// create Tree
struct Node
{
int key;
Node *left, *right;
};
// Function to print all odd nodes
void oddNode(Node* root)
{
if (root != NULL) {
oddNode(root->left);
// if node is odd then print it
if (root->key % 2 != 0)
printf("%d ", root->key);
oddNode(root->right);
}
}
// Driver Code
int main()
{
/* Let us create following BST
5
/ \
3 7
/ \ / \
2 4 6 8 */
Node* root = NULL;
root = insert(root, 5);
root = insert(root, 3);
root = insert(root, 2);
root = insert(root, 4);
root = insert(root, 7);
root = insert(root, 6);
root = insert(root, 8);
oddNode(root);
}
输出应为3,但实际输出为空正确的解决方案:
int oddNode(Node* root)
{
int count = 0;
if (root) {
count += oddNode(root->left);
if (root->key % 2 != 0 && root->key>0) {
printf("%d ", root->key);
++count;
}
count += oddNode(root->right);
}
return count;
}
// Driver Code
int main()
{
/* Let us create following BST
5
/ \
3 7
/ \ / \
2 4 6 8 */
Node node8 = { 8, nullptr, nullptr };
Node node6 = { 6, nullptr, nullptr };
Node node4 = { 4, nullptr, nullptr };
Node node2 = { 2, nullptr, nullptr };
Node node7 = { 7, &node6, &node8 };
Node node3 = { 3, &node2, &node4 };
Node node5 = { 5, &node3, &node7 };
Node *root = &node5;
int count = oddNode(root);
std::cout
<< "\n"
<< "Number of odd nodes: " << count << '\n';
}
int-oddNode(节点*根)
{
整数计数=0;
如果(根){
count+=oddNode(根->左);
如果(root->key%2!=0&&root->key>0){
printf(“%d”,根->键);
++计数;
}
count+=oddNode(根->右);
}
返回计数;
}
//驱动程序代码
int main()
{
/*让我们创建以下BST
5.
/ \
3 7
/ \ / \
2 4 6 8 */
节点node8={8,nullptr,nullptr};
节点node6={6,nullptr,nullptr};
节点node4={4,nullptr,nullptr};
节点node2={2,nullptr,nullptr};
节点node7={7,&node6,&node8};
节点node3={3,&node2,&node4};
节点node5={5,&node3,&node7};
节点*根=&node5;
int count=oddNode(根);
标准::cout
“这似乎是进行调试的最佳时机。”一些程序员说,好吧,但问题是我没有出现错误或类似的情况,我只是得到了一个空屏幕,就是这样。当我说“调试”时我的意思是,您需要使用调试器逐行遍历代码,逐步执行递归调用,并查看发生了什么以及所有涉及的变量都有哪些值。@Someprogrammerdude是的,我得到了-[次1(进程16307)正常退出]因此,函数oddNode
不仅应该打印,还应该返回计数?然后首先应该让它返回一些东西(首先让它返回0
),然后需要考虑如何将递归调用的结果相加。然后需要考虑当条件为真时如何将结果相加。