遍历二叉树(前中后序、层次)

70 阅读1分钟

本文将给出遍历二叉树的多种方法,同时给出简略的说明。

首先对节点进行定义,代码如下。

#include<string>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
 
struct tn
{
	int val;
	tn* left;
	tn* right;
	tn() :val(0), left(nullptr), right(nullptr) {};
	tn(int x):val(x), left(nullptr), right(nullptr) {};
	tn(int x, tn* l, tn* r) :val(x), left(l), right(r) {};
};

首先是用递归前序遍历,代码实现如下。

把将数值压进vector的操作与对左节点递归的操作代码对换,就实现了中序遍历。后序同理。

	{
		//边界条件
		if (node == NULL)
		{
			return;
		}
		//中左右的顺序
		ve.push_back(node->val);
		runTWO(node->left,ve);
		runTWO(node->right, ve);
	}

递归通常可以用堆栈来实现替代,以下代码是迭代法和栈实现非递归遍历二叉树。

由于前序要求输出结果是中左右,因此入栈顺序就应该把左右反过来,右节点先于左节点入栈。

	{
		stack<tn*> st;
		vector<int> ve;
		st.push(root);
		while (!st.empty())
		{
			tn* temp = st.top();
			st.pop();
			if (root == NULL)
			{
				continue;
			}
			ve.push_back(temp->val);
			//由于是栈,因此要先把右节点入栈
			if (temp->right != NULL)
			{
				st.push(temp->right);
			}
			if (temp->left != NULL)
			{
				st.push(temp->left);
			}
		}
		return ve;
	}

除了前中后序,实现二叉树遍历还有层序遍历的手段。

以下代码实现利用队列实现层序遍历二叉树,实现逻辑可以自己画图对照代码进行理解。

	vector<vector<int>> runTHREE(tn* root)
	{
		vector<vector<int>> result ;
		queue<tn*>que;
		que.push(root);
 
		while(!que.empty())
		{
			if (root == NULL)
			{
				continue;
			}
			vector<int>current;
			int size = que.size();
			while (size--)
			{
				current.clear();
				tn* temp = que.front();
				que.pop();
				current.push_back(temp->val);
				if (temp->left != NULL)
				{
					que.push(temp->left);
				}
				if (temp->right != NULL)
				{
					que.push(temp->right);
				}
			}
			result.push_back(current);
		}
		return result;
	}