Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
Challenge 1: Using only 1 queue to implement it.
Challenge 2: Use DFS algorithm to do it.
1.队列
以前一直依次输出每层的节点标号,很简单。但现在需要把每层的标号存在一个二维向量中。
可以在每一层末尾插入一个NULL来区分层次!
/**
* 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> > res;
if(root==NULL){
return res;
}
queue<TreeNode*> Q;
Q.push(root);
Q.push(NULL);
vector<int> level;
while(!Q.empty()){
TreeNode *node=Q.front();
Q.pop();
if(node){
level.push_back(node->val);
if(node->left){
Q.push(node->left);
}
if(node->right){
Q.push(node->right);
}
}else{
res.push_back(level);
level.clear();
if(!Q.empty()){
Q.push(NULL);
}
}
}
return res;
}
};