二叉树的结点个数
非递归的求法很简单,每出队一个结点,count++。递归的解法,从上自下遍历到最底端,返回左右子树结点数+1,代表左右子树的结点再加上父结点的个数。
代码如下:
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
typedef struct node{
char val;
struct node* left;
struct node* right;
}TreeNode,*Tree;
//递归
/*递归到树的最底部,返回左右子树的结点数再+1,表示左右子树再加上父结点*/
int Count(Tree& t){
if(t == NULL) return 0;
return Count(t->left) + Count(t->right) + 1;
}
//非递归
int levelOrder(Tree& t) {
if(t == NULL) return 0;
int count = 0; //结点总数
queue<TreeNode*> q;
q.push(t);
while(!q.empty()){
TreeNode* s = q.front();
count ++;
q.pop();
if(s->left) q.push(s->left);
if(s->right) q.push(s->right);
}
return count;
}
void CreateTree(Tree& t){
char x;
cin>>x;
if(x == '#') t = NULL;
else{
t = new TreeNode;
t->val = x;
CreateTree(t->left);
CreateTree(t->right);
}
}
int main(){
Tree t;
CreateTree(t);
/*
a b d # # e # # c f # # #
*/
cout<<endl<<"非递归:"<<endl;
cout<<levelOrder(t);
cout<<endl<<"递归:"<<endl;
cout<<Count(t);
}
运行结果: