问题描述:
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {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) {
vector<vector<int>> result;
queue<TreeNode*>q; //
vector<int> level; //每层结果
int size,i;
TreeNode* p;
if(root==NULL) return result;
q.push(root); //入队
while(!q.empty()) { //队列中有几个元素就依次遍历每个元素的左右结点
level.clear();
size=q.size();
for(i=0; i<size; i++) {
p=q.front(); //队首元素值赋给p
q.pop(); //出队
level.push_back(p->val);
if(p->left) { //依次压入左右结点元素
q.push(p->left);
}
if(p->right) {
q.push(p->right);
}
}
result.push_back(level); //添加每层数据
}
return result;
// write your code here
}
};
感想:
注意运用队列特性的方法