From 26ba4a11aa92c87a3e756b241958a3c9c0fbae8b Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Thu, 9 Nov 2023 16:18:28 -0500 Subject: [PATCH] adding queue based level order traversal --- lectures/21_hash_tables_II/README.md | 1 + leetcode/p102_level_order_traversal.cpp | 44 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 leetcode/p102_level_order_traversal.cpp diff --git a/lectures/21_hash_tables_II/README.md b/lectures/21_hash_tables_II/README.md index a21fdf0..da45f60 100644 --- a/lectures/21_hash_tables_II/README.md +++ b/lectures/21_hash_tables_II/README.md @@ -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 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 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). diff --git a/leetcode/p102_level_order_traversal.cpp b/leetcode/p102_level_order_traversal.cpp new file mode 100644 index 0000000..febae8d --- /dev/null +++ b/leetcode/p102_level_order_traversal.cpp @@ -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> levelOrder(TreeNode* root) { + vector> result; + std::queue myQueue; + if(root==nullptr){ + return {}; + } + // initial setup of the queue + myQueue.push(root); + while(!myQueue.empty()){ + int size = myQueue.size(); + vector current_level; + // assume every node at the next lever is in the queue, visit them one by one. + for(int i=0;ival); + // 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; + } +};