二叉树的遍历


结点定义

struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}

1、二叉树的前序遍历(递归+非递归)

//递归
void PrevOrder(TreeNode* root)
{
	if (root == nullptr)
		return;
	cout << root->val << " ";
	PrevOrder(root->left);
	PrevOrder(root->right);
}

//非递归
//方法1
void PrevOrderNR(TreeNode* root)
{
	stack<TreeNode*> st;//存节点指针
	st.push(root);
	while (!st.empty())
	{
		TreeNode* cur = st.top();
		st.pop();
		cout << cur->val << " ";
		//前序遍历,先入右再入左,出栈的就是先出左再出右
		if (cur->right != nullptr)
			st.push(cur->right);
		if (cur->left != nullptr)
			st.push(cur->left);
	}
}

//方法2
void PrevOrderNR(TreeNode* root)
{
	stack<TreeNode*> st;//存节点指针

	TreeNode* cur = root;
	while (cur || !st.empty())
	{
		//遍历左子树
		while (cur)
		{
			cout << cur->val << " ";
			st.push(cur);
			cur = cur->left;
		}

		cur = st.top()->right;//cur指向栈顶top元素的右子树
		st.pop();
	}
}

2、二叉树的序遍中历(递归+非递归)

//递归
void InOrder(TreeNode* root)
{
	if (root == nullptr)
		return;
	InOrder(root->left);
	cout << root->val << " ";
	InOrder(root->right);
}

//非递归
void InOrderNR(TreeNode* root)
{
	stack<TreeNode*> st;//存节点指针
	TreeNode* cur = root;
	while (cur || !st.empty())
	{
		//存放cur和cur的左子树,节点指针存在栈中
		while (cur)
		{
			st.push(cur);
			cur = cur->left;
		}
		cur = st.top()->right;//cur指向栈顶top元素的右子树
		cout << st.top()->val << " ";//栈顶元素就是左子树
		st.pop();
	}
}

3、二叉树的序遍后历(递归+非递归)

void PostOrder(TreeNode* root)
{
	if (root == nullptr)
		return;
	PostOrder(root->left);
	PostOrder(root->right);
	cout << root->val << " ";
}

//非递归
void PostOrderNR(TreeNode* root)
{
	stack<TreeNode*> st;
	TreeNode* cur = root;//记录当前结点
	TreeNode* prev = nullptr;//记录当前结点的上一个结点

	while (cur || !st.empty())
	{
		while (cur)
		{
			st.push(cur);
			cur = cur->left;
		}

		TreeNode* top = st.top();

		//条件成立表明右子树访问结束,需要访问val,并更新prev    
		if (top->right == nullptr || top->right == prev)
		{
			cout << top->val << " ";
			prev = top;
			st.pop();
		}
		//条件不成立表明右子树还没有访问完毕,继续访问右子树
		else
		{
			cur = top->right;
		}
	}
}

4、二叉树的层序遍历

void levelOrder(TreeNode* root)
{
	if (root == nullptr)
		return;
	queue<TreeNode*> q;
	q.push(root);
	while (!q.empty())
	{
		TreeNode* cur = q.front();//获取队头元素
		q.pop();
		cout << cur->val << " ";
		if (cur->left != nullptr)//左不为空,就将左结点入队列
			q.push(cur->left);
		if (cur->right != nullptr)//右不为空,就将右结点入队列
			q.push(cur->right);
	}
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值