/*用到的二叉树
1
/ \
4 2
/ \ / \
3 5 null 6
*/
#include <bits/stdc++.h>
#include <queue>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
//创建二叉树
TreeNode *buildTree(vector<int> &nums, int index)
{
if (index >= nums.size() || nums[index] < 0)
{
return nullptr; // 值为负的时候,设置为空节点
}
TreeNode *root = new TreeNode(nums[index]);
root->left = buildTree(nums, 2 * index + 1);
root->right = buildTree(nums, 2 * index + 2);
return root;
}
//结果的输出
void coutTree(vector<int> res)
{
for (auto i : res)
cout << i << " ";
cout << endl;
}
// 前序遍历
void inorder_1(TreeNode *root, vector<int> &res_1)
{
if (!root)
return;
res_1.push_back(root->val);
inorder_1(root->left, res_1);
inorder_1(root->right, res_1);
}
// 中序遍历
void inorder_2(TreeNode *root, vector<int> &res_2)
{
if (!root)
{
return;
}
inorder_2(root->left, res_2);
res_2.push_back(root->val);
inorder_2(root->right, res_2);
}
// 后序遍历
void inorder_3(TreeNode *root, vector<int> &res_3)
{
if (!root)
return;
inorder_3(root->left, res_3);
inorder_3(root->right, res_3);
res_3.push_back(root->val);
}
// 深度优先
void inorder_dfs(TreeNode *root, vector<int> &res_dfs)
{
if (!root)
return;
stack<TreeNode *> nodeStack;
nodeStack.push(root);
TreeNode *node;
while (!nodeStack.empty())
{
node = nodeStack.top();
cout << node->val << " ";
nodeStack.pop();
if (node->right)
nodeStack.push(node->right);
if (node->left)
nodeStack.push(node->left); // 将左子树后压入栈中
}
cout << endl;
}
// 广度优先
void inorder_bfs(TreeNode *root, vector<int> &res_bfs)
{
if (!root)
return;
queue<TreeNode *> qbfs;
qbfs.push(root);
while (!qbfs.empty())
{
cout << qbfs.front()->val << " ";
if (qbfs.front()->left != nullptr)
qbfs.push(qbfs.front()->left);
if (qbfs.front()->right != nullptr)
qbfs.push(qbfs.front()->right);
qbfs.pop();
}
cout << endl;
}
// 中转函数
void inorderTraversal(TreeNode *root)
{
vector<int> res_1; // 前
vector<int> res_2; // 中
vector<int> res_3; // 后
vector<int> res_dfs; // 深度优先
vector<int> res_bfs; // 广度优先
cout << "前序遍历:";
inorder_1(root, res_1);
coutTree(res_1);
cout << "中序遍历:";
inorder_2(root, res_2);
coutTree(res_2);
cout << "后序遍历:";
inorder_3(root, res_3);
coutTree(res_3);
cout << "深度优先遍历:";
inorder_dfs(root, res_dfs);
cout << "广度优先遍历:";
inorder_bfs(root, res_bfs);
}
int main()
{
vector<int> nums = {1, 4, 2, 3, 5, -1, 6};
TreeNode *root = buildTree(nums, 0);
inorderTraversal(root);
system("pause");
return 0;
}
结果如下所示:
代码不足的部分请多多包涵,总之基本上就是这个实现。