typedef struct CSNode
{
Elemtype data;
struct CSNode *firstchild,*nextsibling;
}CSNode,*CSTree;
typedef struct node{
CSTree child;
struct node *next;
} * nd;
count(CSTree T){
nd p,q,e;
CSTree r;
int i,c;
//i记录层数,c记录每层的结点数;
p=(nd)malloc(sizeof(struct node));
p->child=T;p->next=NULL;
q=p;i=1;
while(q){
c=0;p->next=NULL;
while(q){
r=q->child->firstchild;
while(r){
c++;
if(r->firstchild){
e=(nd)malloc(sizeof(struct node));e->child=r->firstchild;e->next=NULL;
e->next=p->next;p->next=e;
}
r=r->nextsibling;
}
e=q;q=q->next;free(e);
}
printf("第%d层结点数为:%d\n",i,c);
i++;
q=p->next;
}
}
实现代码 :
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) throws Exception {
//初始化树
Node root = new Node("第0层");
Node node1_1 = new Node("第一层(1)");
Node node2_1 = new Node("第二层(1)");
Node node2_2 = new Node("第二层(2)");
root.child = node1_1;
node1_1.child = node2_1;
node2_1.brother = node2_2;
//输出每一层的节点数
Tree tree = new Tree(root);
Map
for(Integer level : counts.keySet()) {
System.out.println("第" + level + "层:" + counts.get(level));
}
}
}
//树节点结构
class Node{
public Node(){}
public Node(String name){this.name = name;}
public String name;
public Node child;
public Node brother;
}
//树定义
class Tree{
private Node root;
public Tree(){}
public Tree(Node root){this.root = root;}
//统计每层节点数,算法思想:广度遍历
public Map
Map
if(root != null) {
Queue