二叉树的遍历总结

        二叉树是一种重要的基础数据结构,其定义本身是递归的。二叉树有三种遍历方式,同时既可以利用递归来遍历,又可以利用栈来进行非递归遍历。下面是我个人总结出来的遍历。

首先定义二叉树的结构:

struct BTreeNode
{
	char data;
	struct BTreeNode* lchild;
	struct BTreeNode* rchild;
	BTreeNode(char ch) :data(ch), lchild(NULL), rchild(NULL){}
};

一 前序遍历(根->左子树->右子树)

递归遍历:

void pre_order(BTreeNode* p)
{
	if (p != NULL)
	{
		cout << p->data << " ";
		pre_order(p->lchild);
		pre_order(p->rchild);
	}
}

非递归遍历:

void pre_order1(BTreeNode* p)
{
	stack<BTreeNode*> s;
	if (p == NULL) return;
	s.push(p);
	while (!s.empty())
	{
		p = s.top();
		s.pop();
		cout << p->data << " " << endl;
		if (p->rchild) s.push(p->rchild);
		if (p->lchild) s.push(p->lchild);
	}
}

二 中序遍历(左子树->根->右子树)

递归遍历:

void in_order(BTreeNode* p)
{
	if (p != NULL)
	{
		in_order(p->lchild);
		cout << p->data << " ";
		in_order(p->rchild);
	}
}

非递归遍历:

void in_order1(BTreeNode* p)
{
	stack<BTreeNode*> s;
	BTreeNode* head = p;
	while (!s.empty() || head != NULL)
	{
		while (head)
		{
			s.push(head);
			head = head->lchild;
		}
		if (!s.empty())
		{
			head = s.top();
			s.pop();
			cout << head->data << " ";
			head = head->rchild;
		}
	}
}

三 后序遍历(左子树->右子树->根)

递归遍历:

void post_order(BTreeNode* p)
{
	if (p != NULL)
	{
		post_order(p->lchild);
		post_order(p->rchild);
		cout << p->data << " ";
	}
}

非递归遍历:

void post_order1(BTreeNode* p)
{
	BTreeNode *p1, *q;
	q = NULL;
	p1 = p;
	stack<BTreeNode*> s;
	do
	{
		while (p1)
		{
			s.push(p1);
			p1 = p1->lchild;
		}
		q = NULL;
		while (!s.empty())
		{
			p1 = s.top();
			s.pop();
			if (p1->rchild == q)
			{
				cout << p1->data << " ";
				q = p1;
			}
			else
			{
				s.push(p1);
				p1 = p1->rchild;
				break;
			}
		}

	} while (!s.empty());
}


评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值