一个函数,它将树作为参数,并返回已键入的int数
A function that will take a tree as argument and return the number of ints that were typed?
我的项目中需要一个函数,该函数将以树为参数,并返回键入的整数数和正确的调用。
这不就是预购吗?如下所示。请感谢
#include "t.h"
void preorder(tnode * t){
if (t == NULL) return;
cout << t->info <<endl;
preorder(t->left);
preorder(t->right);
}
调用将是预购(t)。
这是我拥有的原始功能
#ifndef T_H
#define T_H
#include <iostream>
#include <iomanip>
using namespace std;
struct tnode {
int info ;
int count;
tnode * right, *left;
};
tnode * insert(int target,tnode * t);
tnode * makenode(int x);
tnode * tsearch(int x,tnode * t);
void inorder(tnode * t);
int height(tnode * t);
int count(tnode * t) ;
int total(tnode * t) ;
#endif
int main() {
int n,c;
tnode * t = NULL, *x;
while (cin >> n) {t=insert(n,t);cout << n <<' ';}
cout << endl;
inorder(t);
cout << endl;
c = count(t);
cout << "count: "<< c <<endl;
cout << endl;
c = height(t);
cout << "height: "<< c <<endl;
cout << endl;
c=200;
while (c-->0) if (x = tsearch(c,t)) cout << c << " is on the tree."<<endl;
return 0;
}
#include "t.h"
int count(tnode * t) {
if (t == NULL) return 0;
return 1 + count(t->left) + count (t->right);
}
#include "t.h"
int height(tnode * t) {
if (t == NULL) return -1;
return 1 + max(height(t->left) , height (t->right));
}
#include "t.h"
//write out t in order
void inorder(tnode * t) {
if (t == NULL) return;
inorder (t->left);//write out lst in order
cout <<setw(5) << t->info <<setw(5) << t->count<< endl;
inorder (t->right);//write out rst in order
}
#include "t.h"
tnode * insert(int x, tnode * t) {
tnode * tmp = tsearch(x,t);
if (tmp != NULL) {
tmp->count++;
return t;
}
if (t == NULL) return makenode(x);
if ( x < t->info ) {
t->left = insert(x,t->left);
return t;
}
t->right = insert(x,t->right);
return t;
}
#include "t.h"
tnode * makenode(int x) {
tnode * t = new tnode;
t->info =x;
t->count =1;
t->right = t->left = NULL;
return t;
}
首先,函数不能为void。它必须返回已键入的int数,因此必须返回int或int*。
其次,这棵树是一棵二叉树吗?它包含了所有类型化的int?如果是这样的话,任何树遍历算法都可以。你只需要一个变量,当你找到一个新节点时,你会增加这个变量(假设它们都存储一个int)。
int preorder(tnode * t){
if (t == NULL) return 0;
else{
return 1 + preorder(t->left) + preorder(t->right);
}
}
如果t不为null,那么它存储了1 int。然后你只需要检查节点的子节点。
当用户键入一个数字时,insert
函数要么插入一个计数为1的新节点,要么添加到现有节点的计数中。您需要汇总树中元素的计数:
int tcount(tnode * t){
if (t == NULL) return 0;
return t->count + tcount(t->left) + tcount(t->right);
}
典型的呼叫是
tnode * root = NULL;
/* insert stuff into the tree */
int count = tcount(root);
相关文章:
- 函数作为模板参数,是否对返回类型强制约束
- 子例程,不使用 pow,并带有参数和返回
- 系统参数信息A 与 SPI_GETMOUSE 返回 0
- 在 c++ 中将函数返回类型指定为模板参数
- 如果返回 -1,时间() 的参数是否被修改?
- 在返回参数列表中C++局部变量(如CodeFights所示)
- is_invocable_r忽略返回参数
- C 功能参数中的返回参数
- 如何在 gmock 中返回参数之一
- 为什么 istream 类的运算符<<在 C++ 中具有引用的返回/参数类型?
- 如果返回参数,是否可以复制省略
- 避免通过引用返回参数
- C/C++ va_list 未正确返回参数
- 返回参数C++的函数
- 为什么在返回参数时不允许RVO
- 如何在createprocess结束后从exe返回参数
- 是否有可能编写一个函数模板来返回参数的数量是否能被N整除?
- 提振.Python多个返回参数
- 伊利德返回参数
- 返回参数的Typename查找