C++使用递归方法构造二叉树,用到二叉树结点,输入为层次遍历序列
时间: 2024-01-07 07:57:09 浏览: 65
#include <iostream>
#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>& nums, int index) {
// 边界条件
if (index >= nums.size() || nums[index] == -1) {
return NULL;
}
// 构造当前结点
TreeNode* root = new TreeNode(nums[index]);
// 递归构造左子树和右子树
root->left = buildTree(nums, 2 * index + 1);
root->right = buildTree(nums, 2 * index + 2);
return root;
}
// 层次遍历二叉树
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
cout << node->val << " ";
if (node->left != NULL) {
que.push(node->left);
}
if (node->right != NULL) {
que.push(node->right);
}
}
}
}
int main() {
vector<int> nums = {1, 2, 3, 4, 5, 6, 7, -1, -1, 8, 9};
TreeNode* root = buildTree(nums, 0);
levelOrder(root);
return 0;
}
阅读全文