Merge pull request #56 from mgisr/master

fix(codes/cpp/include/TreeNode.hpp):  fix 'vecToTree' function
pull/63/head
Yudong Jin 2 years ago committed by GitHub
commit 6dba81d145
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -23,25 +23,28 @@ struct TreeNode {
* @param list * @param list
* @return TreeNode* * @return TreeNode*
*/ */
TreeNode* vecToTree(vector<int> list) { TreeNode *vecToTree(vector<int> list) {
TreeNode *root = new TreeNode(list[0]); if (list.empty()) {
queue<TreeNode*> que; return nullptr;
que.emplace(root); }
int i = 1;
while(!que.empty()) { auto *root = new TreeNode(list[0]);
TreeNode *node = que.front(); queue<TreeNode *> que;
size_t n = list.size(), index = 1;
while (index < n) {
auto 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;
} }
@ -52,7 +55,7 @@ TreeNode* vecToTree(vector<int> list) {
* @param val * @param val
* @return TreeNode* * @return TreeNode*
*/ */
TreeNode* getTreeNode(TreeNode *root, int val) { TreeNode *getTreeNode(TreeNode *root, int val) {
if (root == nullptr) if (root == nullptr)
return nullptr; return nullptr;
if (root->val == val) if (root->val == val)

Loading…
Cancel
Save