102. Binary Tree Level Order Traversal
Description
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]
]
My Solution
/**
* 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){
vector<vector<int>> ans;
vector<int> temp;
queue<TreeNode*> qu;
TreeNode* p = root;
if (p){
qu.push(p);
qu.push(NULL);
}
while(!qu.empty()){
while(qu.front()){
p = qu.front();
if (p->left){
qu.push(p->left);
}
if (p->right){
qu.push(p->right);
}
temp.push_back(p->val);
qu.pop();
}
qu.pop();
if (!temp.empty()){
ans.push_back(temp);
}
temp.clear();
if (qu.empty()){
break;
}
qu.push(NULL);
}
return ans;
}
};
网友评论