文章
105
粉丝
69
获赞
117
访问
61.3k
#include<bits/stdc++.h>
using namespace std;
string data;
// 定义二叉树节点
typedef struct Tree {
char val;
Tree *left, *right;
Tree(char x) : val(x), left(nullptr), right(nullptr) {}
}Tree;
// 层次遍历建树
Tree* build(const string& data) {
if (data.empty() || data[0] == '#') return NULL;
queue<Tree*> q;
Tree* root = new Tree(data[0]);
q.push(root);
int i = 1;
while (!q.empty() && i < data.size()) {
Tree* node = q.front();
q.pop();
char leftChar = data[i++];
char rightChar = (i < data.size()) ? data[i++] : '#';
if (leftChar != '#') {
node->left = new Tree(leftChar);
q.push(node->left);
}
if (rightChar != '#') {
node->right = new Tree(rightChar);
q.push(node->right);
}
}
return root...
登录后发布评论
暂无评论,来抢沙发