我需要一個函數在我的項目中,將樹作爲參數,並返回鍵入和正確調用的整數數量。一個函數,它將樹作爲參數並返回鍵入的整數數量?
難道它只是預購嗎?如下所示。請。謝謝
#include "t.h"
void preorder(tnode * t){
if (t == NULL) return;
cout << t->info <<endl;
preorder(t->left);
preorder(t->right);
}
呼叫將預訂(噸)。
這是原來的功能,我有
#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;
}
的問題是有點模糊。這棵樹代表了一個表達式的解析樹(在這種情況下,整數的數量是葉*的數量*),還是僅僅是一個整數的二叉樹(在這種情況下,它意味着節點的數量)?另外,你並沒有通過你的函數傳遞一個累加器,所以你需要一個全局計數器(或者修改函數參數來包含一個in-out'int *'參數作爲你的計數器累加器)。 – WhozCraig