文章
37
粉丝
1
获赞
353
访问
24.6k
#include<bits/stdc++.h>
using namespace std;
// 定义二叉树节点结构体
typedef struct node {
string data; // 节点存储的数据(字符串类型)
node* lchild; // 左孩子指针
node* rchild; // 右孩子指针
} *BiTree;
/**
* 函数:build
* 功能:根据层序遍历序列(vector<string>)构建二叉树
* 说明:使用队列实现,"null" 表示该位置为空节点
*/
BiTree build(vector<string> v) {
// 如果输入为空数组,或者第一个元素就是 null,说明是一棵空树
if (v.size() == 0 || v[0] == "null") return nullptr;
queue<node*> q; // 使用队列辅助进行层序构建
// 创建根节点,并将其入队
BiTree root = new node{stoi(v[0]), nullptr, nullptr};
q.push(root);
size_t idx = 1; // idx 用于遍历字符串数组 v,从第 1 个元素(即根节点的左孩子)开始
while (idx < v.size() && !q.empty()) {
BiTree curr = q.front(); // 取出队头节点,准备为它连接左右孩子
q.pop();
// 尝试连接左孩子
if (idx < v.size() && v[idx] != "null") {
curr->left = new node{stoi(v[idx]), nullptr, nullptr};
q.push(curr->left); // 左孩子存在,入队,以后也要为它找孩子
}
idx++; // 无论是否为 null,数组指针都要往后移一位
// 尝...
登录后发布评论
暂无评论,来抢沙发