mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-20 21:52:30 +08:00
Optimize arrToTree function
in java, cpp, py, go, js, ts.
This commit is contained in:
@ -27,23 +27,24 @@ struct TreeNode {
|
||||
* @return TreeNode*
|
||||
*/
|
||||
TreeNode *vecToTree(vector<int> list) {
|
||||
if (list.empty()) {
|
||||
if (list.empty())
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto *root = new TreeNode(list[0]);
|
||||
queue<TreeNode *> que;
|
||||
size_t n = list.size(), index = 1;
|
||||
while (index < n) {
|
||||
que.emplace(root);
|
||||
size_t n = list.size(), index = 0;
|
||||
while (!que.empty()) {
|
||||
auto node = que.front();
|
||||
que.pop();
|
||||
|
||||
if (++index >= n) break;
|
||||
if (index < n) {
|
||||
node->left = new TreeNode(list[index++]);
|
||||
node->left = new TreeNode(list[index]);
|
||||
que.emplace(node->left);
|
||||
}
|
||||
if (++index >= n) break;
|
||||
if (index < n) {
|
||||
node->right = new TreeNode(list[index++]);
|
||||
node->right = new TreeNode(list[index]);
|
||||
que.emplace(node->right);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user