fix(codes/cpp/include/TreeNode.hpp): Fix 'vecToTree' function

This commit is contained in:
mgisr 2022-12-01 09:09:34 +08:00
parent acfdc713ba
commit 84825a22d9

View File

@ -24,24 +24,27 @@ struct TreeNode {
* @return TreeNode* * @return TreeNode*
*/ */
TreeNode *vecToTree(vector<int> list) { TreeNode *vecToTree(vector<int> list) {
TreeNode *root = new TreeNode(list[0]); if (list.empty()) {
return nullptr;
}
auto *root = new TreeNode(list[0]);
queue<TreeNode *> que; queue<TreeNode *> que;
que.emplace(root); size_t n = list.size(), index = 1;
int i = 1; while (index < n) {
while(!que.empty()) { auto node = que.front();
TreeNode *node = que.front();
que.pop(); que.pop();
if(list[i] != INT_MAX) {
node->left = new TreeNode(list[i]); if (index < n) {
node->left = new TreeNode(list[index++]);
que.emplace(node->left); que.emplace(node->left);
} }
i++; if (index < n) {
if(list[i] != INT_MAX) { node->right = new TreeNode(list[index++]);
node->right = new TreeNode(list[i]);
que.emplace(node->right); que.emplace(node->right);
} }
i++;
} }
return root; return root;
} }