二叉树叶子结点的个数
非递归的求法,用广度优先遍历,每出队一个结点,判断它是不是叶子结点。递归的做法,先由上自下遍历,等遍历到叶子处再逐层返回左右子树的叶子结点总和,最后得到整棵树的叶子结点数。
那么同样的,类似二叉树有多少个度为 1 的结点,二叉树有多少个度为 2 的结点,把这段代码的判断条件修改就可以。
代码如下:
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
typedef struct node{
char val;
struct node* left;
struct node* right;
}TreeNode,*Tree;
//非递归
/*由根向下进行广度优先遍历,每遍历一个结点判断一次*/
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();
if(s->left == NULL && s->right == NULL)
count ++; //结点左右子树为空是叶子
q.pop();
if(s->left) q.push(s->left);
if(s->right) q.push(s->right);
}
return count;
}
//递归
/*由上自下寻找叶子结点,遍历到最底部逐层往上汇报*/
int Count(Tree& t){
if(t == NULL) return 0; //空树返回0
else if(t->left == NULL && t->right ==NULL)
return 1; //左右子树为空是叶子结点,返回1
return Count(t->left) + Count(t->right); //返回左右子树的叶子结点和
}
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);
}
运行结果: