题目:
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] ]
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int> > ret; if (!root) return ret; vector<int> tmp_ret; deque<TreeNode *> currLevel, nextLevel; currLevel.push_back(root); while ( !currLevel.empty() ) { while ( !currLevel.empty() ) { TreeNode * tmp = currLevel.front(); currLevel.pop_front(); tmp_ret.push_back(tmp->val); if ( tmp->left ) nextLevel.push_back(tmp->left); if ( tmp->right ) nextLevel.push_back(tmp->right); } ret.push_back(tmp_ret); tmp_ret.clear(); std::swap(currLevel, nextLevel); } return ret; } };
tips:
核心:两个队列技巧
1. 采用两个队列,一个队列存放本层TreeNode,另一个队列存放下一层的TreeNode
2. 本层Node逐个出队的同时加入tmp_ret的vector,下一层的Node逐个入队
3. 本层Node全部出队之后,tmp_ret推入ret(并注意清空tmp_ret,第一次没有清空tmp_ret没有AC)
4. 逐个时候currLevel队列已经空了,nextLevel队列存放的都是下一层的节点,利用swap操作交换二者。(这个交换是O(1)的指针交换)
完毕。
======================================
一些关于二叉树 deque queue的参考资料:
http://www.cnblogs.com/way_testlife/archive/2010/10/07/1845264.html
http://stackoverflow.com/questions/2247982/deque-vs-queue-in-c
=======================================
第二次过这道题,用双队列的思路实现的,代码一次AC。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int> > ret; queue<TreeNode*> curr; queue<TreeNode*> next; if ( root ) curr.push(root); while ( !curr.empty() ) { vector<int> tmp; while ( !curr.empty() ) { tmp.push_back(curr.front()->val); if ( curr.front()->left ) next.push(curr.front()->left); if ( curr.front()->right ) next.push(curr.front()->right); curr.pop(); } ret.push_back(tmp); std::swap(next, curr); } return ret; } };