编写程序实现二叉树的先序、中序、后序、层序遍历; 2. 对二叉树实现求深度、层数运算
时间: 2023-07-10 08:11:45 浏览: 120
好的,我来为您解答这两个问题。
1. 实现二叉树的遍历
先定义二叉树的结构体:
```C++
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(nullptr), right(nullptr) {};
};
```
接下来是遍历函数的实现:
```C++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// 先序遍历
void preorderTraversal(TreeNode* root) {
if (root == nullptr) return;
cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root == nullptr) return;
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root == nullptr) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->val << " ";
}
// 层序遍历
void levelorderTraversal(TreeNode* root) {
if (root == nullptr) 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);
}
}
}
```
2. 实现求深度、层数运算
```C++
// 求深度
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
int leftDepth = maxDepth(root->left);
int rightDepth = maxDepth(root->right);
return max(leftDepth, rightDepth) + 1;
}
// 求层数
void dfs(TreeNode* root, int level, vector<int>& res) {
if (root == nullptr) return;
if (res.size() < level) res.push_back(root->val);
dfs(root->left, level + 1, res);
dfs(root->right, level + 1, res);
}
vector<int> levelOrder(TreeNode* root) {
vector<int> res;
dfs(root, 1, res);
return res;
}
```
希望这些代码可以帮助到您。
阅读全文