二叉树

ACM竞赛不常用,PAT倒是常用到

大体两种实现方式:指针,数组

指针实现,有利于理解数据结构的内在和提高能力,但竞赛实用性差,竞赛常用数组实现

数据结构学习时应该用指针实现,具体应用时用数组较好

指针实现:

大概就是先记录数据和左右孩子编号,再去递归建树或者层序建树(层序用队列实现),具体实现略

基于普通指针实现比较简单,基于C++封装实现还要建立节点类和二叉树类

数组实现:

用三个数组,数组长度为节点最大个数。data[N],left[N],right[N],data数组用于保存当前下标对应节点的数据,left和right数组用于保存左右儿子节点的下标


法一:基于C++类封装实现

#include "stdafx.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
#define MAXN 100005
class BinaryTree {
private:
	int n;
	int data[MAXN], left[MAXN], right[MAXN];
public:
	BinaryTree(int t) :n(t) {
		for (int i = 0; i < n; i++) {
			cin >> data[i] >> left[i] >> right[i];
		}
	}
	int findRoot() {
		for (int i = 0; i < n; i++) {
			if (left[i] == -1 && right[i] == -1) {
				return i;
			}
		}
	}
	//...
	//...
	//...其他函数略
};
int main(){
	int n,root;
	BinaryTree *tree;//由于三个数组太大,所以在堆区申请内存
	while (scanf("%d", &n) != EOF) {
		tree = new BinaryTree(n);
		root = tree->findRoot();
		//...
		//...
		//...
		//...其他具体需求略
		delete tree;
	}
	return 0;
}

法二:普通全局数组实现

#include "stdafx.h"
#include <cstdio>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
#define MAXN 100005
int data[MAXN],left[MAXN],right[MAXN];
int root, n;
int main(){
	while (scanf("%d", &n) != EOF) {
		for (int i = 0; i < n; i++) {
			cin >> ::data[i] >> ::left[i] >> ::right[i];
			if (::left[i] == -1 && ::right[i] == -1) {
				root = i;
			}
		}
		//...
		//...
		//...
		//...其他具体需求略
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值