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

 

 

 

#include <iostream>
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;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值