Last active
January 6, 2018 19:51
-
-
Save sourabh2k15/cc7619e36dbe6238483fd4decbc1b361 to your computer and use it in GitHub Desktop.
102. Binary Tree Level Order Traversal Solution using 2 queues
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| vector<vector<int>> levelOrder(TreeNode* root) { | |
| queue<TreeNode*> even; | |
| queue<TreeNode*> odd; | |
| vector<vector<int>> result; | |
| even.push(root); | |
| while(!even.empty() || !odd.empty()){ | |
| vector<int> level; | |
| if(odd.empty()){ | |
| // while even not empty, transfer kids of falling out nodes to odd | |
| while(!even.empty()){ | |
| TreeNode* curr = even.front(); even.pop(); | |
| if(curr){ | |
| level.push_back(curr->val); | |
| odd.push(curr->left); | |
| odd.push(curr->right); | |
| } | |
| } | |
| } | |
| else if(even.empty()){ | |
| // if even is empty, transfer kids of falling out nodes to even | keep juggling | |
| while(!odd.empty()){ | |
| TreeNode* curr = odd.front(); odd.pop(); | |
| if(curr){ | |
| level.push_back(curr->val); | |
| even.push(curr->left); | |
| even.push(curr->right); | |
| } | |
| } | |
| } | |
| result.push_back(level); | |
| } | |
| result.pop_back(); | |
| return result; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment