//层序遍历+层序构造
void cengxuB(TreeNode* head, vector<int>& ans) {
queue<TreeNode*>q;
TreeNode* b;
if (!head)return;
q.push(head);
while (!q.empty()) {
b = q.front();
q.pop();
ans.push_back(b->val);
if (b->left) {
q.push(b->left);
}
if (b->right) {
q.push(b->right);
}
}
}
TreeNode* cengxuG(vector<int>ans) {
queue<TreeNode*>q;
if (ans.empty())return nullptr;
TreeNode* head = new TreeNode(ans[0]);
q.push(head);
TreeNode* bt;
int i = 1;
while (!q.empty()) {
bt = q.front();
q.pop();
if (i < ans.size()) {
bt->left = new TreeNode(ans[i]);
q.push(bt->left);
i++;
}
else bt->left = nullptr;
if (i < ans.size()) {
bt->right = new TreeNode(ans[i]);
q.push(bt->right);
i++;
}
else bt->right = nullptr;
}
return head;
}
int main() {
vector<int>ans, ans1;
int n;
while (cin >> n) {
ans.push_back(n);
if (cin.get() == '\n')break;
}
TreeNode* temp = cengxuG(ans);
cengxuB(temp, ans1);
return 0;
}
C++层序遍历与层序构造
最新推荐文章于 2024-06-18 13:52:22 发布