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] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
思路:
重点在于每层元素个数不定,如何标记一层的结束,往堆栈里push很多NULL来表示空位这种方案,会造成Memory Limit Exceeded。
可以采取记下每层的NULL数量,下层翻倍这种方式计数,满额push标记NULL作为一层的结束
代码:
1 vector<vector<int> > levelOrder(TreeNode *root) { 2 vector<vector<int> > orders; 3 if(root == NULL) 4 return orders; 5 6 vector<int> vtmp; 7 queue<TreeNode*> tque; 8 tque.push(root); 9 tque.push(NULL); 10 11 int size = 2; 12 int count = 0; 13 int zero = 0;//该层的NULL数 14 while(!tque.empty()){ 15 TreeNode * tmp = tque.front();//$$$$ 16 tque.pop();//void pop() 17 18 if(tmp == NULL){//NULL标识一层的结束 19 if(!vtmp.empty())//最后一行可能不满 20 orders.push_back(vtmp); 21 vtmp.clear(); 22 continue; 23 } 24 vtmp.push_back(tmp->val); 25 if(tmp->left != NULL){ 26 tque.push(tmp->left); 27 count++; 28 } 29 else 30 zero++; 31 if(tmp->right != NULL){ 32 tque.push(tmp->right); 33 count++; 34 } 35 else 36 zero++; 37 38 if(count + zero == size){ 39 tque.push(NULL); 40 count = 0; 41 size *= 2; 42 zero = zero * 2; 43 } 44 } 45 return orders; 46 }