Let's see this problem from leetcode.
if you have already learn about tree traversals, then we know that there are basically two types of traversal technique we have. DFS and BFS. so to solve these kind of problem we will use one of these techniques. even whenever there is question related to traversal in Tree data structure you should only think about these two and you will get the solution. so here we are going to use BFS, because it uses queue data structure and according to the question it will be a good choice.
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> mainans;vector<int>v;
queue<TreeNode*> q;
if(root==NULL){
return mainans;
}
q.push(root);
q.push(NULL);
TreeNode *ans;
while(!q.empty()){
ans=q.front();
if(ans){
v.push_back(ans->val);
}
q.pop();
if(!ans){
if(q.empty()){
mainans.push_back(v);
break;
}
else{
q.push(NULL);
mainans.push_back(v);
v.clear();
continue;
}
}
if(ans->left!=NULL && ans->right!=NULL){
q.push(ans->left);
q.push(ans->right);
}
if(ans->left!=NULL && ans->right==NULL){
q.push(ans->left);
}
if(ans->left==NULL && ans->right!=NULL){
q.push(ans->right);
}
if(ans->left==NULL && ans->right==NULL){
continue;
}
}
return mainans;
}
Comments
Post a Comment