二叉树坐标计算

数据结构与算法分析——c语言描述 练习4.33 答案


只是计算完坐标,还没写展示。有空在把展示写了。


#include"fatal.h"
#include<stdlib.h>

typedef int ElementType;

struct AvlNode;
typedef struct AvlNode *Position;
typedef struct AvlNode *AvlTree;

struct AvlNode {
	ElementType element;
	AvlTree left;
	AvlTree right;
	int isDeleted;
	int height;
	int x;
	int y;
};

int RandInt(int i, int j) {
	int temp;
	temp = (int)(i + (1.0*rand() / RAND_MAX)*(j - i));
	return temp;
}

AvlTree makeRandomAVLTree(int H) {
	if (H >= 0) {
		AvlTree t = malloc(sizeof(struct AvlNode));
		if (t == NULL)
			Error("OUT OF MEMORY");
		t->left = makeRandomAVLTree(H - 1);
		t->right = makeRandomAVLTree(H - 2);

		if (t->left == NULL&&t->right == NULL) {
			t->element = rand();
		}
		else if (t->left == NULL)
			t->element = RandInt(0, t->right->element);
		else if (t->right == NULL)
			t->element = RandInt(t->left->element, RAND_MAX);
		else
			t->element = RandInt(t->left->element, t->right->element);
		t->height = H;
		return t;
	}
	return NULL;
}


void calcX(AvlTree t, int *lastX) {
	if (t) {
		calcX(t->left, lastX);
		t->x = (++*lastX);
		calcX(t->right, lastX);
	}
}

void calcY(AvlTree t,int TreeHeight){
	if (t) {
		t->y = TreeHeight- t->height;
		calcY(t->left,TreeHeight);
		calcY(t->right,TreeHeight);
	}
	

}

void CalculateCoordinates(AvlTree t) {
	int x = 0;
	calcX(t, &x);
	calcY(t,t->height);
}

void dir(AvlTree t) {
	if (t) {
		fprintf(stderr, "%d  x:%d  y: %d\n",t->element, t->x,t->y);
		dir(t->left);

		dir(t->right);
	}

}

int main() {
	AvlTree t = makeRandomAVLTree(3);
	CalculateCoordinates(t);
	dir(t);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值