二叉树深度,广度遍历

#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX_OP 10

typedef struct Node{
   int key;
struct Node* lchild,* rchild;
}Node;


Node* getNewNode(int key) {
	Node* p = (Node*)malloc(sizeof(Node));
	p->key = key;
	p->lchild = p->rchild = NULL;
	return p;

}


Node* insert(Node* root, int key) {
	if (root == NULL)return getNewNode(key);
	if (rand() % 2)root->lchild = insert(root->lchild, key);
	else root->rchild = insert(root->rchild, key);
	return root;

}


void clear(Node* root) {
	if (root == NULL) return;
	clear(root->lchild);
	clear(root->rchild);
	free(root);
	return;
}
Node* queue[MAX_OP+5];
int head, tail;
void bfs(Node* root) {//深度优先遍历
	head = tail = 0;
	queue[tail++] = root;
	while (head < tail) {
		Node* node = queue[head];
		printf("\nnode:%d\n", node->key);
		if (node->lchild) {
			queue[tail++] = node->lchild;
			printf("\t%d->%d(left)\n", node->key, node->lchild->key);

		}
		if (node->rchild) {
			queue[tail++] = node->rchild;
			printf("\t%d->%d(right)\n", node->key, node->rchild->key);
		}
		head++;
	}
	return;
}
int tot = 0;
void dfs(Node* root) {//广度优先遍历
	if (root == NULL)return;
	int start, end;
	tot += 1;
	start = tot;
	if (root->lchild)dfs(root->lchild),printf("left\n");
	if (root->rchild)dfs(root->rchild),printf("right\n");
	tot += 1;
	end = tot;
	printf("%d:[%d,%d]\n", root->key, start, end);
	return;
}
int main() {
	srand(time(0));
	Node* root = NULL;
	for (int i = 0; i < MAX_OP; i++) {
		root = insert(root, rand() % 100);


	}
	bfs(root);
	dfs(root);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值