/* 输出二叉树每层的节点*/
typedef struct node{
struct node* left;
struct node* right;
node(){
left = NULL;
right = NULL;
};
} node,*nodeptr;
void count(vector<node> layerlist){
if (layerlist.size() == 0)
return;
vector<node> vec;
int countt = 0;
for(auto c : layerlist){//对该层每个节点检查,存在一个节点数量加一, 如果该节点有孩子,则将孩子节点加入到下一层节点列表
countt ++;
if(c.left)
vec.push_back(*c.left);
if(c.right)
vec.push_back(*c.right);
}
cout<<countt<<endl;
count(vec);//处理下一层节点
}
int main(){
node a;
node b;
node c;
node d;
node e;
node f;
node g;
a.left = &b;
a.right = NULL;
b.right = &c;
b.left = &d;
c.left = &e;
c.right = &f;
d.left = &g;
vector<node> aa = { a };
count(aa);
}
输出二叉树每层节点数量
最新推荐文章于 2023-06-25 17:03:05 发布