102. Binary Tree Level Order Traversal
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,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
解题思路:
采用双队列来处理。
用当前队列current来处理本层的所有节点,将本层信息记录在vector中。用next来记录下一层的节点信息。
当前队列处理后,将本层信息的vector存储到结果vector中。清空存储本层信息的vector。将current和next交换。然后重新处理current队列。
代码如下:
/**
* 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>> result;
queue<TreeNode *> current,next;
vector<int> level;
if(NULL == root)
return result;
current.push(root);
while(current.size() > 0)
{
while(current.size() > 0)
{
TreeNode *p = current.front();
current.pop();
level.push_back(p->val);
if(p->left)
next.push(p->left);
if(p->right)
next.push(p->right);
}
result.push_back(level);
level.clear();
current.swap(next);
}
return result;
}
};
2016-08-05 17:21:32
转载于:https://blog.51cto.com/qiaopeng688/1834819