Advertisement
expired6978

Binary Tree Level Order Traversal

May 10th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10.  #include <queue>
  11.  
  12. class Solution {
  13. public:
  14.     vector<vector<int>> levelOrder(TreeNode* root) {
  15.         vector<vector<int>> result;
  16.         if(!root)
  17.             return result;
  18.        
  19.         TreeNode* node = nullptr;
  20.         queue<TreeNode*> q;
  21.         q.push(root);
  22.         q.push(nullptr);
  23.        
  24.         vector<int> v;
  25.         while(!q.empty())
  26.         {
  27.             node = q.front();
  28.             q.pop();
  29.            
  30.             if(q.empty()) {
  31.                 result.push_back(v);
  32.                 break;
  33.             }
  34.            
  35.             if(node) {
  36.                 if(node->left)
  37.                     q.push(node->left);
  38.                 if(node->right)
  39.                     q.push(node->right);
  40.                 v.push_back(node->val);
  41.             } else {
  42.                 q.push(nullptr);
  43.                 result.push_back(v);
  44.                 v.clear();
  45.             }
  46.         }
  47.        
  48.         return result;
  49.     }
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement