二叉树的遍历(递归)

二叉树 :二叉树是一棵特殊的树,二叉树每个节点最多有两个孩子结点,分别称为左孩子和右孩子。
满二叉树 :高度为N的满二叉树有2^N- 1个节点的二叉树。
完全二叉树: 若设二叉树的深度为h,除第h 层外,其它各层(1~h-1) 的结点数都达到最大个数,第h 层所有的结点都连续集中在最左
边,这就是完全二叉树。

如图,是一个完全二叉树。


★前序遍历(先根遍历):【1 2 3 4 5 6】

(1):先访问根节点; 

(2):前序访问左子树;

(3):前序访问右子树;

代码如下:

#include<iostream>
#include<queue>
#include<stack>
using namespace std;

template <typename T>
struct BinaryTreeNode
{
	BinaryTreeNode<T>* _Left;
	BinaryTreeNode<T>* _Right;
	T _data;

	BinaryTreeNode(const T& x)
		:_Left(NULL)
		, _Right(NULL)
		,_data(x)
	{
	}
};

template <typename T>
class BinaryTree
{
	typedef BinaryTreeNode<T> Node;
public:
	BinaryTree()
		:_root(NULL)
	{
	}
	BinaryTree(const T *a, size_t size, int invalid)
	{
		int index = 0;
		_root=_CreatBinaryTree(a, size,invalid,index);
	}
	BinaryTree(const BinaryTree<T>& t)
	{
		_root = _Copy(t._root);
	}

	BinaryTree& operator=(const BinaryTree<T>& t)
	{
		if (this != &t)
		{
			_Destory(_root);
			_root = _Copy(t._root);
		}
		return *this;
	}

	~BinaryTree()
	{
		_Destory(_root);
		_root = NULL;
	}

	void PreOrder()
	{
		 _PreOrder(_root);
		 cout << endl;
	}

	void InOrder()
	{
		 _InOrder(_root);
		 cout << endl;
	}

	void PostOrder()
	{
		 _PostOrder(_root);
		 cout << endl;
	}

	
protected:
	Node* _root;

	Node* _CreatBinaryTree(const T* a, size_t size, const T& invalid, int& index)
	{
		Node* root = NULL;
		if (index < size && a[index] !=invalid)
		{
			root = new Node(a[index]);
			root->_Left = _CreatBinaryTree(a, size, invalid, ++index);
			root->_Right = _CreatBinaryTree(a, size, invalid, ++index);
		}
		return root;
	}

	Node* _Copy(Node* root)
	{
		if (root == NULL)
		{
			return NULL;
		}
		else
		{
			Node* newroot = new Node(root->_data);
			newroot->_Left = _Copy(root->_Left);
			newroot->_Right = _Copy(root->_Right);
		}
		return newroot;
	}

	void _Destory(Node* &root)
	{
		if (root == NULL)
		{
			return;
		}
		if (root->_Left == NULL&&root->_Right == NULL)
		{
			delete root;
			root = NULL;
			return;
		}

		_Destory(root->_Left);
		_Destory(root->_Right);
		delete root;
	}

	void _PreOrder(Node* root)
	{
		if (root == NULL)
		{
			return;
		}
		cout << root->_data << " ";
		_PreOrder(root->_Left);
		_PreOrder(root->_Right);
		
	}


★中序遍历: 【3 2 4 1 6 5】

(1):中序访问左子树;

(2):访问根节点;

(3):中序访问右子树; 

代码如下:

void _InOrder(Node* root)
	{
		if (root == NULL)
		{
			return;
		}
		else
		{
			_InOrder(root->_Left);
			cout << root->_data << " ";
			_InOrder(root->_Right);
		}
	}


★后序遍历(后根遍历):【3 4 2 6 5 1】

(1):后序访问左子树;

(2):后序访问右子树;

(3):访问根节点; 

代码如下:

void _PostOrder(Node* root)
	{
		if (root == NULL)
		{
			return;
		}
		else
		{
			_PostOrder(root->_Left);
			_PostOrder(root->_Right);
			cout << root->_data << " ";
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值