二叉树的构建与遍历完整代码c++
时间: 2023-11-20 22:07:17 浏览: 99
完整代码如下:
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 通过先序遍历和中序遍历构建二叉树
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.empty() || inorder.empty()) return NULL;
int rootVal = preorder[0];
TreeNode* root = new TreeNode(rootVal);
int pos = 0;
while (inorder[pos] != rootVal) pos++;
vector<int> leftPreorder(preorder.begin() + 1, preorder.begin() + pos + 1);
vector<int> leftInorder(inorder.begin(), inorder.begin() + pos);
root->left = buildTree(leftPreorder, leftInorder);
vector<int> rightPreorder(preorder.begin() + pos + 1, preorder.end());
vector<int> rightInorder(inorder.begin() + pos + 1, inorder.end());
root->right = buildTree(rightPreorder, rightInorder);
return root;
}
// 先序遍历
void preorderTraversal(TreeNode* root) {
if (!root) return;
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (!root) return;
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (!root) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
// 层序遍历
void levelOrderTraversal(TreeNode* root) {
if (!root) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* cur = q.front();
q.pop();
cout << cur->val << " ";
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
cout << endl;
}
}
int main() {
vector<int> preorder = {1, 2, 4, 5, 3, 6, 7};
vector<int> inorder = {4, 2, 5, 1, 6, 3, 7};
TreeNode* root = buildTree(preorder, inorder);
cout << "先序遍历结果:";
preorderTraversal(root);
cout << endl;
cout << "中序遍历结果:";
inorderTraversal(root);
cout << endl;
cout << "后序遍历结果:";
postorderTraversal(root);
cout << endl;
cout << "层序遍历结果:" << endl;
levelOrderTraversal(root);
return 0;
}
```
其中,我们以先序遍历和中序遍历构建二叉树,然后分别实现了先序遍历、中序遍历、后序遍历和层序遍历的方法。在main函数中,我们构建了一个二叉树,并分别调用了这四种遍历方法,输出了遍历的结果。
阅读全文