永发信息网

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

答案:3  悬赏:60  手机版
解决时间 2021-01-27 05:04
  • 提问者网友:山高云阔
  • 2021-01-26 22:28
编写算法,对一颗以孩子-兄弟链表表示的树统计每层结点的个数.(是每层结点个数不单单是叶子结点个数)
最佳答案
  • 五星知识达人网友:未来江山和你
  • 2021-01-26 23:58
实现代码 :

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;
}
全部回答
  • 1楼网友:神的生死簿
  • 2021-01-27 01:58
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楼网友:孤老序
  • 2021-01-27 01:04
int leafcount_cstree(cstree t)//求孩子兄弟链表表示的树t的叶子数目 { if(!t->firstchild) return 1; //叶子结点 else { count=0; for(child=t->firstchild;child;child=child->nextsibling) count+=leafcount_cstree(child); return count; //各子树的叶子数之和 } }//leafcount_cstree
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯