ALDS1_7_B:Binary Trees

二叉树的表达,题目链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_7_B

思路:建立一个二叉树,每个节点如下:

struct node {
	int parent,left,right;
};

parent存父节点,left和right分别存左孩子和右孩子。

初始化全部属性都赋为NIL(-1)

求深度的方法有两种,同 https://blog.csdn.net/qq_33982232/article/details/80454501

求高度的方法,也有两种,第一种是建立一个高度数组,存放每个节点的高度,递归填充数组。

我采用的是另一种方法,对每一个节点求高度的时候都递归求解。

代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxx = 28;
const int NIL = -1;
struct node {
	int parent,left,right;
};
node tree[maxx];

int get_depth(int x){
	int depth=0;
	while(tree[x].parent!=NIL){
		x=tree[x].parent;
		depth++;
	}
	return depth;
}

int get_height(int x){
	int h1=0,h2=0;
	if((tree[x].left==NIL)&&(tree[x].right==NIL)) return 0;
	if(tree[x].left!=NIL) h1=get_height(tree[x].left)+1;
	if(tree[x].right!=NIL) h2=get_height(tree[x].right)+1;
	return max(h1,h2);
}

int main (){
	for(int i = 0;i<maxx;i++) {
	tree[i].parent=NIL;
	tree[i].left=NIL;
	tree[i].right=NIL;	
	}
	int n;
	cin>>n;
	int a,b,c;
	for(int i=0;i<n;i++){
		cin>>a>>b>>c;
		tree[a].left=b;
		tree[a].right=c;
		if(b!=NIL) tree[b].parent=a;
		if(c!=NIL) tree[c].parent=a;
	}
	for(int i=0;i<n;i++){
		printf("node %d: parent = %d",i,tree[i].parent);
		if(tree[i].parent==NIL) printf(", sibling = -1");
		else if(tree[tree[i].parent].left==i) printf(", sibling = %d",tree[tree[i].parent].right);
		else printf(", sibling = %d",tree[tree[i].parent].left);
		if(tree[i].left!=NIL){
			if(tree[i].right!=NIL) printf(", degree = 2"); else printf(", degree = 1");
		}
		else{
			if(tree[i].right!=NIL) printf(", degree = 1"); else printf(", degree = 0");
		}
		printf(", depth = %d",get_depth(i));
		printf(", height = %d",get_height(i));
		if(tree[i].parent==NIL) printf(", root");
		else if(tree[i].left==NIL&&tree[i].right==NIL) printf(", leaf");
		else printf(", internal node");
		printf("\n");
	}
	return 0;
}

错点:

1.读入过程中,如下代码, 注意,所有的节点输入值和i无关,节点的序号由输入值a决定,这个错误同ALDS1_7_A中的错误

	for(int i=0;i<n;i++){
		cin>>a>>b>>c;
		tree[a].left=b;
		tree[a].right=c;
		if(b!=NIL) tree[b].parent=a;
		if(c!=NIL) tree[c].parent=a;
	}

2.读入过程中,要加两个if的判断,否则会出现对tree[-1]的访问,造成越界。

		if(b!=NIL) tree[b].parent=a;
		if(c!=NIL) tree[c].parent=a;

3.求高度的过程中要加这一句话,否则会死循环。(这个不用写...)

if((tree[x].left==NIL)&&(tree[x].right==NIL)) return 0;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值