-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to fix the bug of arrayToTree function? #678
Comments
The https://github.com/krahets/hello-algo/blob/main/codes/python/modules/tree_node.py |
@justin-tse Please track this issue, thanks! |
1 similar comment
@justin-tse Please track this issue, thanks! |
Recursion is ok (that's what java does), but I just wonder if it can be achieved using a queue (arrayToTree in js)? |
Of course, just also push function arrToTree(arr) {
if (arr.length === 0) return null;
const root = new TreeNode(arr[0]);
const queue = [root];
let i = 0;
while (queue.length) {
const node = queue.shift();
if (node) {
if (++i >= arr.length) break;
if (arr[i] !== null) node.left = new TreeNode(arr[i]);
if (++i >= arr.length) break;
if (arr[i] !== null) node.right = new TreeNode(arr[i]);
queue.push(node.left, node.right)
} else {
i += 2;
queue.push(null, null)
}
}
return root;
} |
Thank you very much, you solved my confusion, thanks again for the great code. hh |
I think this implementation might fail for the cases ended by
|
Passed this case, and I tested that all places where arrToTree is used in the code can output correctly.
|
It works well |
I found a bug in the arrayToTree function, I tried to modify the logic of arrayToTree, but it didn't solve the problem, please help me!Here are the details:
If you want to pass the above case, how to modify the logic of the arrayToTree function?
The text was updated successfully, but these errors were encountered: