leetcode 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]
]
bfs层序遍历整颗树。
/**
* 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) {
queue<TreeNode*> q;
vector<vector<int> > ans;
if (root == nullptr) return ans;
q.push(root);
while (!q.empty()) {
vector<int> v;
int n = q.size();
while (n-- > 0) {
TreeNode* u = q.front();
q.pop();
//cout << u->val << endl;
v.push_back(u->val);
if (u->left != nullptr) q.push(u->left);
if (u->right != nullptr) q.push(u->right);
}
ans.push_back(v);
}
return ans;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: