Description:
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] ]
Code:
1 vector<vector<int>> levelOrder(TreeNode* root) { 2 deque<TreeNode*>a; 3 deque<TreeNode*>b; 4 if (root) 5 a.push_back(root); 6 7 TreeNode*p = NULL; 8 vector<vector<int>> result; 9 10 while (!a.empty()) 11 { 12 vector<int>temp; 13 if (!a.empty() ) 14 { 15 while (!a.empty() ) 16 { 17 p = a.front(); 18 a.pop_front(); 19 temp.push_back(p->val); 20 if (p->left) 21 b.push_back(p->left); 22 if (p->right) 23 b.push_back(p->right); 24 } 25 result.push_back(temp); 26 } 27 28 while (!b.empty()) 29 { 30 a.push_back(b.front()); 31 b.pop_front(); 32 } 33 } 34 return result; 35 }