给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {3,9,20,#,#,15,7} :
3
/
9 20
/
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
这道题用队列去做,把一个节点入队,再把左子树和右子树入队,然后依次出队就可以了。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrder(TreeNode *root) {
// write your code here
vector<vector<int> > result;
if (!root) return result;
queue<TreeNode*> que;
que.push(root);
int len;
while (!que.empty()) {
vector<int> res;
len = que.size();
while (len--) {
TreeNode *temp = que.front();
res.push_back(temp->val);
que.pop();
if (temp->left) que.push(temp->left);
if (temp->right) que.push(temp->right);
}
result.push_back(res);
}
return result;
}
};