二叉树的前序中序后序层序遍历总结(C++版)
1、前序遍历(根左右)
递归:没什么好说的
void preOrder(TreeNode* root)
{
if (!root) return;
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
非递归:借助栈
前序遍历根左右,先将当前节点打印,并将其进栈,节点指向其左孩子,直到左孩子为空。这时相当于左子树已经遍历完了,需要访问右节点,将当前元素指向栈顶元素右孩子,弹出栈顶元素
void preOrder(TreeNode* root)
{
if (!root) return;
stack<TreeNode*> s;
auto cur = root;
while (cur || s.size())
{
while (cur)
{
cout << cur->val << " ";
s.push(cur);
cur = cur->left;
}
auto t = s.top();
s.pop();
cur = t->right;
}
}
2、中序遍历(左根右)
递归:没什么好说的
void inOrder(TreeNode* root)
{
if (!root) return;
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
非递归:借助栈
中序遍历左根右,和前序遍历类似,只不过访问节点从第一次进栈时就访问变成出栈时才访问
void inOrder(TreeNode* root)
{
if (!root) return;
stack<TreeNode*> s;
auto cur = root;
while (cur || s.size())
{
while (cur)
{
s.push(cur);
cur = cur->left;
}
auto t = s.top();
s.pop();
cout << t->val << " ";
cur = t->right;
}
}
3、后序遍历(左右根)
递归:没什么好说的
void postOrder(TreeNode* root)
{
if (!root) return;
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
非递归:借助栈
后序遍历左右根,反过来是根右左,而我们知道前序遍历是根左右,所以可以首先模拟前序遍历的过程,同时将前序遍历中左右子树遍历过程对换,最后将遍历数组翻转就可以得到后序遍历
void postOrder(TreeNode* root)
{
if (!root) return;
stack<TreeNode*> s;
vector<int> v;
auto cur = root;
while (cur || s.size())
{
while (cur)
{
v.push_back(cur->val);
s.push(cur);
cur = cur->right;
}
auto t = s.top();
s.pop();
cur = t->left;
}
reverse(v.begin(), v.end());
for (auto s : v) cout << s << " ";
}
4、层序遍历
层序遍历通常借助于队列实现。当根节点不为空时,将根节点入队。当队列不为空时,访问队列头,将队头元素出队,同时将队头元素的非空左右儿子节点依次入队
void bfsTree(TreeNode* root)
{
if (!root) return;
queue<TreeNode*> q;
q.push(root);
while (q.size())
{
auto t = q.front();
q.pop();
cout << t->val << " ";
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
}