地址:http://oj.leetcode.com/problems/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,#,#,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.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.
#我的答案
/**
* Definition for binary tree
* 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) {
int cur=0, cnt=0;
TreeNode *pnode;
vector<vector<int>> vv;
vector<int> vi; // 保存每层的输出节点值
vector<int> vn; // 记录每层含有的节点数
queue<TreeNode*> q;
vn.push_back(1); // level 0 有一个节点
q.push(root);
if (root != 0) while(!q.empty()){ // 广度优先搜索
pnode = q.front();
q.pop();
vi.push_back(pnode->val);
if (++cnt == 1) // 输出的是当前层第一个节点
vn.push_back(0); // 为存储下一层节点开辟空间
if (pnode->left != 0){
q.push(pnode->left);
vn[cur+1]++;
}
if (pnode->right != 0){
q.push(pnode->right);
vn[cur+1]++;
}
if (cnt == vn[cur]){ // 当前level所有节点输出完毕,保存结果并更新相关计数
cur++;
cnt = 0;
vv.push_back(vi);
vi.clear();
}
}
return vv;
}
};