adding queue based level order traversal

This commit is contained in:
Jidong Xiao
2023-11-09 16:18:28 -05:00
parent 151f59ee5d
commit 26ba4a11aa
2 changed files with 45 additions and 0 deletions

View File

@@ -166,3 +166,4 @@ but requires more work to get right.
- [Leetcode problem 508: Most Frequent Subtree Sum](https://leetcode.com/problems/most-frequent-subtree-sum/). Solution: [p508_most_frequent_subtree_sum.cpp](../../leetcode/p508_most_frequent_subtree_sum.cpp). - [Leetcode problem 508: Most Frequent Subtree Sum](https://leetcode.com/problems/most-frequent-subtree-sum/). Solution: [p508_most_frequent_subtree_sum.cpp](../../leetcode/p508_most_frequent_subtree_sum.cpp).
- [Leetcode problem 225: Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/). Solution: [p225_stack_using_queues.cpp](../../leetcode/p225_stack_using_queues.cpp). - [Leetcode problem 225: Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/). Solution: [p225_stack_using_queues.cpp](../../leetcode/p225_stack_using_queues.cpp).
- [Leetcode problem 232: Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/). Solution: [p232_queue_using_stacks.cpp](../../leetcode/p232_queue_using_stacks.cpp). - [Leetcode problem 232: Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/). Solution: [p232_queue_using_stacks.cpp](../../leetcode/p232_queue_using_stacks.cpp).
- [Leetcode problem 102: Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/). Solution: [p102_level_order_traversal.cpp](../../leetcode/p102_level_order_traversal.cpp).

View File

@@ -0,0 +1,44 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
std::queue<TreeNode*> myQueue;
if(root==nullptr){
return {};
}
// initial setup of the queue
myQueue.push(root);
while(!myQueue.empty()){
int size = myQueue.size();
vector<int> current_level;
// assume every node at the next lever is in the queue, visit them one by one.
for(int i=0;i<size;i++){
TreeNode* current = myQueue.front();
myQueue.pop();
if(current!=nullptr){
current_level.push_back(current->val);
// before we get to the next level, push every node of the next level into the queue.
if(current->left!=nullptr){
myQueue.push(current->left);
}
if(current->right!=nullptr){
myQueue.push(current->right);
}
}
}
result.push_back(current_level);
}
return result;
}
};