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

再学C的数据结构---二叉树递归遍历

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

再学C的数据结构---二叉树递归遍历

 

 

 

#include 
using namespace std;


class Node
{
public:
	char m_value;  //数据
	Node* m_left;  //指向左孩子
	Node* m_right; //指向右孩子

public:
	Node(const char v = '*') :m_value{ v }, m_left{ nullptr }, m_right{ nullptr } {}
};


class BTree
{
	using root = Node*;
private:
	root m_root; //根结点
	char m_flag;   //标记位

public:
	BTree() :m_root{ nullptr }, m_flag{ '*' } {}
	root Create(const char*& str)
	{
		if (*str == '*')
		{
			return nullptr;
		}
		else
		{
			Node* root = new Node{ *str };
			root->m_left = Create(++str);
			root->m_right = Create(++str);
			return root;
		}
	}

	root& GetRoot()
	{
		return m_root;
	}

	void PreOrder(const root const bt) const
	{
		if (bt == nullptr)
		{
			return;
		}
		else
		{
			cout << bt->m_value << " ";
			PreOrder(bt->m_left);
			PreOrder(bt->m_right);
		}
	} 

	void InOrder(const root const bt) const
	{
		if (bt == nullptr)
		{
			return;
		}
		else
		{
			InOrder(bt->m_left);
			cout << bt->m_value << " ";
			InOrder(bt->m_right);
		}
	}
	
	void PostOrder(const root const bt) const
	{
		if (bt == nullptr)
		{
			return;
		}
		else
		{
			PostOrder(bt->m_left);
			PostOrder(bt->m_right);
			cout << bt->m_value << " ";
		}
	}

	int Size(const root const bt)const
	{
		if (bt == nullptr)
		{
			return 0;
		}
		else
		{
			return Size(bt->m_left) + Size(bt->m_right) + 1;
		}
	}

	int Height(const root const bt)const
	{
		if (bt == nullptr)
		{
			return 0;
		}
		else
		{
			int lh = Height(bt->m_left);
			int rh = Height(bt->m_right);
			return lh > rh ? lh + 1 : rh + 1;
		}
	}
};


int main()
{
	BTree bt;
	const char* str = "abd**eh***cf*i**g**";
	bt.GetRoot() = bt.Create(str);
	bt.PreOrder(bt.GetRoot());
	cout << "n";
	bt.InOrder(bt.GetRoot());
	cout << "n";
	bt.PostOrder(bt.GetRoot());

	cout << endl;

	cout << bt.Height(bt.GetRoot()) << endl;

	cout << bt.Size(bt.GetRoot()) << endl;

	return 0;
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1028520.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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