Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / 9 20 / 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Solution:
1 vector<vector<int> > levelOrder(TreeNode *root) { 2 vector<vector<int> > nums; 3 if(root == NULL) 4 return nums; 5 vector<TreeNode *> level; 6 level.push_back(root); 7 8 while(true){ 9 if(level.size() == 0 ) 10 break; 11 vector<int> level_num; 12 vector<TreeNode *> new_level; 13 for(auto item : level) { 14 level_num.push_back(item->val); 15 if(item->left != NULL) 16 new_level.push_back(item->left); 17 if(item->right != NULL) 18 new_level.push_back(item->right); 19 } 20 nums.push_back(level_num); 21 level = new_level; 22 } 23 return nums; 24 }