From 84825a22d9b64a2e02dffbb0dcdc3535b1072606 Mon Sep 17 00:00:00 2001 From: mgisr Date: Thu, 1 Dec 2022 09:09:34 +0800 Subject: [PATCH] fix(codes/cpp/include/TreeNode.hpp): Fix 'vecToTree' function --- codes/cpp/include/TreeNode.hpp | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/codes/cpp/include/TreeNode.hpp b/codes/cpp/include/TreeNode.hpp index 614d799..7be2b8d 100644 --- a/codes/cpp/include/TreeNode.hpp +++ b/codes/cpp/include/TreeNode.hpp @@ -23,25 +23,28 @@ struct TreeNode { * @param list * @return TreeNode* */ -TreeNode* vecToTree(vector list) { - TreeNode *root = new TreeNode(list[0]); - queue que; - que.emplace(root); - int i = 1; - while(!que.empty()) { - TreeNode *node = que.front(); +TreeNode *vecToTree(vector list) { + if (list.empty()) { + return nullptr; + } + + auto *root = new TreeNode(list[0]); + queue que; + size_t n = list.size(), index = 1; + while (index < n) { + auto node = que.front(); 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); } - i++; - if(list[i] != INT_MAX) { - node->right = new TreeNode(list[i]); + if (index < n) { + node->right = new TreeNode(list[index++]); que.emplace(node->right); } - i++; } + return root; } @@ -52,7 +55,7 @@ TreeNode* vecToTree(vector list) { * @param val * @return TreeNode* */ -TreeNode* getTreeNode(TreeNode *root, int val) { +TreeNode *getTreeNode(TreeNode *root, int val) { if (root == nullptr) return nullptr; if (root->val == val)