栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++实现二叉树

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++实现二叉树

C++实现二叉树
  1. 实现二叉树的初始化。
  2. 实现二叉树的尾部增加,删除,查找某一节点的父节点,左孩子,右孩子,左兄弟,右兄弟结点。
  3. 实现先序遍历,中序遍历及后序遍历。

实现代码:

#pragma once

template 
class CMyTree_Arr {
	T		*pBuff;
	size_t	len;
	size_t	maxSize;
public:
	CMyTree_Arr() {
		pBuff = nullptr;
		len = maxSize = 0;
	}
	~CMyTree_Arr() {
		clear();
	}
public:
	void clear() {
		if (pBuff) {
			delete[] pBuff;
		}
		pBuff = nullptr;
		len = maxSize = 0;
	}

	bool find(T const& findVal) const {
		return _find(findVal) != -1;
	}

	void appendNode(T const& data) {	//尾部追加
		if (len >= maxSize) {
			maxSize = maxSize + ((maxSize >> 1) > 1 ? (maxSize >> 1) : 1);
			T* temp = new T[maxSize];
			for (size_t i = 0; i < len; ++i) {
				temp[i] = pBuff[i];
			}
			if (pBuff) {
				delete[] pBuff;
			}
			pBuff = temp;
		}
		pBuff[len++] = data;
	}

	void initTree(T arr[], int length) {	//数组初始化数组
		clear();
		if (length > 0){
			maxSize = len = length;
			pBuff = new T[maxSize];
			for (size_t i = 0; i < length; ++i) {
				pBuff[i] = arr[i];
			}
		}
	}

	void printfTree() {
		_printfTree(0);//根节点下标0开始
	}

	T getLeftChildVal(int index) const {	//得到左子树的元素
		if ((2 * index + 1) >= len || index < 0) {
			throw "out_range";
		}
		return pBuff[2 * index + 1];
	}
	T getRightChildVal(int index) const {	//得到右子树的元素
		if ((2 * index + 2) >= len || index < 0) {
			throw "out_range";
		}
		return pBuff[2 * index + 2];
	}
	T getParentVal(int index) const {	//得到父亲的元素
		if ((index - 1) < 0 || index>=len ) {
			throw "out_range";
		}
		return pBuff[(index - 1) >> 1];
	}
	T getLeftBrotherVal(int index) const {	//得到左兄弟的元素
		if (index <= 0 || index >= len) {
			throw "out_range";
		}
		if (index % 2 == 1) {
			throw "isleft";
		}
		return pBuff[index - 1];
	}
	T getRightBrotherVal(int index) const {	//得到右兄弟的元素
		if (index <= 0 || index >= len) {
			throw "out_range";
		}
		if (index % 2 == 0) {
			throw "isright";
		}
		return pBuff[index + 1];
	}

private:
	int _find(T const& findVal) const {
		for (size_t i = 0; i < len; ++i) {
			if (pBuff[i] == findVal) {
				return i;
			}
		}
		return -1;
	}

	void _printfTree(int index) {
		if (index < len) {
			//先序
			printf("%dn", pBuff[index]);
			_printfTree(index * 2 + 1);
			_printfTree(index * 2 + 2);

			中序
			//_printfTree(index * 2 + 1);
			//printf("%dn", pBuff[index]);
			//_printfTree(index * 2 + 2);

			后序
			//_printfTree(index * 2 + 1);
			//_printfTree(index * 2 + 2);
			//printf("%dn", pBuff[index]);
		}
	}
};

主函数代码:

#include "myTree_Arr.h"
int _tmain(int argc, _TCHAR* argv[])
{
	CMyTree_Arr mt;
	int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	mt.appendNode(3);
	mt.initTree(arr, 10);
	mt.printfTree();
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942450.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号