【C++】二叉树的基本操作

<pre name="code" class="cpp">#include<iostream>
#include<queue>
#include<stack>
using namespace std;
struct BinaryTreeNode
{
	char _value;          //节点值
	BinaryTreeNode*_left; //左孩子
	BinaryTreeNode*_right;//右孩子
	BinaryTreeNode(const char value)
		:_value(value)
		,_left(NULL)
		, _right(NULL)
	{}
};
class BinaryTree
{
public:
	BinaryTree(const char *str)
		:_root(NULL)
	{
		_CreatBinaryTree(_root, str);
	}
	//先序遍历
	void RootSort()
	{
		cout << "先序遍历:" << endl;
		_RootSort(_root);
		cout << endl;
	}
	//中序遍历
	void MidSort()
	{
		cout << "中序遍历:" << endl;
		_MidSort(_root);
		cout << endl;
	}
	//后序遍历
	void BackSort()
	{
		cout << "后序遍历:" << endl;
		_BackSort(_root);
		cout << endl;
	}


	
	//层序遍历
	//思想:队列的先进先出
	void LevelSort()
	{
		cout << "层序遍历:" << endl;
		queue<BinaryTreeNode*>q;
		if (_root)
		{
			q.push(_root);
		}
		while (!q.empty())
		{
			BinaryTreeNode*front = q.front();
			q.pop();
			cout << front->_value << " ";
			if (front->_left)
			{
				q.push(front->_left);
			}
			if (front->_right)
			{
				q.push(front->_right);
			}
		}
		cout << endl;
	}
	//节点个数
	int Size()
	{
		cout << "节点个数为:";
		return _Size(_root);
	}
	int Depth()
	{
		cout << "二叉树深度为:";
		return _Depth(_root);
	}
protected:
	void _CreatBinaryTree(BinaryTreeNode*&root, const char*&str)
	{
		if (*str != '#'&&*str != '\0')
		{
			root = new BinaryTreeNode(*str);
			_CreatBinaryTree(root->_left, ++str);
			if (*str != '\0')
			{
				_CreatBinaryTree(root->_right, ++str);
			}
		}
	}
	void _RootSort(BinaryTreeNode*&root)
	{
		if (root)
		{
			cout << root->_value << " ";
			_RootSort(root->_left);
			_RootSort(root->_right);
		}
	}
	void _MidSort(BinaryTreeNode*&root)
	{
		if (root)
		{
			_MidSort(root->_left);
			cout << root->_value << " ";
			_MidSort(root->_right);
		}
	}
	void _BackSort(BinaryTreeNode*&root)
	{
		if (root)
		{
			_BackSort(root->_left);
			_BackSort(root->_right);
			cout << root->_value << " ";
		}
	}
	int _Size(BinaryTreeNode*&root)
	{
		if (root==NULL)
		{
			return 0;
		}
		else
		{
			return 1 + _Size(root->_left) + _Size(root->_right);
		}
	}
	int _Depth(BinaryTreeNode*&root)
	{
		if (root == NULL)
		{
			return 0;
		}
		if (root->_left == NULL&&root->_right == NULL)
		{
			return 1;
		}
		return 1 + (_Depth(root->_left) > _Depth(root->_right)
			? _Depth(root->_left) : _Depth(root->_right));
	}
private:
	BinaryTreeNode*_root;
};
void Test()
{
	BinaryTree bt1("123##4##5678");
	bt1.RootSort();
	bt1.MidSort();
	bt1.BackSort();
	bt1.LevelSort();
	cout << bt1.Size() << endl;
	cout << bt1.Depth() << endl;
}
int main()
{
	Test();
	system("pause");
	return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值