/**
* 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
//运用队列来实现广度搜索
queue<TreeNode *> que;
vector<vector<int>> result;
if ( root == nullptr) {
return result;
}
que.push(root);
while (!que.empty()) {
int size = que.size();
vector<int> list;
for(int i = 0; i != size; ++i) {
TreeNode *temp = que.front();
que.pop();
list.push_back(temp -> val);
if (temp -> left) {
que.push(temp -> left);
}
if (temp -> right) {
que.push(temp -> right);
}
}
result.push_back(list);
}
return result;
}
};
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)