编写算法,对一颗以孩子-兄弟链表表示的树统计每层结点的个数.(是每层结点个数不单单是叶子结点个数)

2024-12-27 03:26:48
推荐回答(2个)
回答1:

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;
}
}

回答2:

实现代码 :

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 counts = tree.countEveryLevel();
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 countEveryLevel() {
Map countMap = new TreeMap();
if(root != null) {
Queue queue = new LinkedList();
queue.offer(new Object[]{root, 0});
while(!queue.isEmpty()) {
Object[] objs = queue.poll();
Node node = (Node)objs[0];
int level = (Integer)objs[1];
if(countMap.get(level) == null) {
countMap.put(level, 1);
} else {
countMap.put(level, countMap.get(level) + 1);
}
if(node.child != null) {
queue.offer(new Object[]{node.child, level + 1});
}
if(node.brother != null) {
queue.offer(new Object[]{node.brother, level});
}
}
}
return countMap;
}