二叉树的前中后遍历-递归和非递归
Posted 穿迷彩服的鲨鱼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树的前中后遍历-递归和非递归相关的知识,希望对你有一定的参考价值。
// 二叉树的前中后遍历-递归和非递归.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<vector>
#include<stack>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
};
/*前序遍历--递归*/
void PreoederDFS(TreeNode* root, vector<int>& result)
{
if (root == nullptr)
{
return;
}
result.push_back(root->val);
PreoederDFS(root->left, result);
PreoederDFS(root->right, result);
}
vector<int> PreoederTraversalDfs(TreeNode* root)
{
vector<int> result;
if (root == nullptr)
{
return result;
}
PreoederDFS(root, result);
return result;
}
/*前序遍历--栈*/
vector<int> PreoederTraversalStack(TreeNode* root)
{
vector<int> result;
if (root == nullptr)
{
return result;
}
TreeNode* tmpNode = nullptr;
stack<TreeNode*> stackTreeode;
stackTreeode.push(root);
while (!stackTreeode.empty())
{
tmpNode = stackTreeode.top();
stackTreeode.pop();
if (tmpNode != nullptr)
{
result.push_back(tmpNode->val);
stackTreeode.push(tmpNode->right);
stackTreeode.push(tmpNode->left);
}
}
return result;
}
/*中序遍历--递归*/
void InorderDFS(TreeNode* root, vector<int>& result)
{
if (root == nullptr)return;
InorderDFS(root->left, result);
result.push_back(root->val);
InorderDFS(root->right, result);
}
vector<int> InorderTraversalDfs(TreeNode* root)
{
if (root == nullptr)return {};
vector<int> result;
InorderDFS(root, result);
return result;
}
/*中序遍历--非递归(栈)*/
vector<int> InorderTraversal(TreeNode* root)
{
if (root == nullptr)return{};
vector<int> result;
stack<TreeNode*> stackTreeNode;
while (root || !stackTreeNode.empty())
{
while (root)
{
stackTreeNode.push(root);
root = root->left;
}
root = stackTreeNode.top();
stackTreeNode.pop();
result.push_back(root->val);
root = root->right;
}
return result;
}
/*后续遍历--递归*/
void PostorderDfs(TreeNode* root, vector<int>& result)
{
if (!root)return;
PostorderDfs(root->left, result);
PostorderDfs(root->right, result);
result.push_back(root->val);
}
vector<int> PostorderTraversalDfs(TreeNode* root)
{
if (!root)return{};
vector<int> result;
PostorderDfs(root, result);
return result;
}
/*后序遍历--栈*/
vector<int> PostorderTraversal(TreeNode* root)
{
if (root == nullptr)return{};
vector<int> result;
stack<TreeNode*> stackTreeNode;
TreeNode* cur = root;
TreeNode* last = nullptr;
while (cur || !stackTreeNode.empty())
{
while (cur)
{
stackTreeNode.push(cur);
cur = cur->left;
}
TreeNode* top = stackTreeNode.top();
if (top->right == nullptr)
{
result.push_back(top->val);
stackTreeNode.pop();
last = top;
}
else if (top->right == last)
{
result.push_back(top->val);
stackTreeNode.pop();
top = last;
}
else
{
cur = top->right;
}
}
return result;
}
以上是关于二叉树的前中后遍历-递归和非递归的主要内容,如果未能解决你的问题,请参考以下文章