Level Order traversal Segmentation fault - c++

I a m trying a simple level order traversal of a Binary tree,but it says I am having an segfault.I am putting up the code for the function which I am using.
#include<queue>
/*
struct node
{
int data;
node* left;
node* right;
}*/
void LevelOrder(node * root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node* t;
t=q.front();
cout<<t->data;
q.push(t->left);
q.push(t->right);
q.pop();
}
}

You need to check if left and right are null.
if (t->left) {
q.push(t->left);
}
if (t->right) {
q.push(t->right);
}
And if root can be null, you also need to check it.

Related

Binary Search Tree leaf count issue

I desperately need help finding the problem in my code, I'm sure it's narrowed down to the countLeaves function. I can't seem to get it to print out no matter how I alter it. I'm pretty new to C++ but I'd really appreciate anything anyone can offer me! I will post the header, function, and main in that order.
#include <iostream>
//#include<stack>
//#include<queue>
#ifndef BSTFunction
#define BSTFunction
using namespace std;
typedef int num;
class Node{
public:
num info;
Node* left;
Node* right;
Node(); // Valuetype to num
Node(num);
};
class BST{
public:
Node* findNode(num);
Node* findParent(num);
Node* findrightnode(Node*);
void inorder(Node*);
Node* root;
Node* curr;
//Was public:
BST();
void insert(num);
void inorderTraversal(); //was traverse
num search();
void custom_print();
int countLeaves(Node* T);
};
#endif
Function.cpp
#include <iostream>
#include <queue>
#include "BSTFunction.hpp"
Node::Node(){
left=right=NULL;
}
Node::Node(num val){
info=val;
left=right=NULL;
}
//constructor
BST::BST(){
root=curr=NULL;
}
//insert a node with value val in tree
void BST::insert(num val){
if(root==NULL)
root = new Node(val);
else{
Node* p =findNode(val);
if(p==0) {
//cout<<"fine1";
Node* parent=root;
if (p != root)
parent = findParent(val);
if(val>parent->info) parent->right=new Node(val);
else parent->left=new Node(val);
}//cout<<"fine2";
}
}
//remove the node if value is val
//fins node with a value key
Node* BST::findNode(num key){
Node* p =root;
while((p!=NULL)&&(p->info!=key)){
if(key<p->info)p=p->left;
else p=p->right;
}
return p;
}
//find parent of a node with value key
Node* BST::findParent(num key){
Node* p =root;
Node* q=0;
while((p!=NULL)&&(p->info!=key)){
q=p;
if(key<p->info)p=p->left;
else p=p->right;
}
return q;
}
//finds the most right of a node p(means immediate succesor of p in inorder representation)
//Node* BST::findrightnode(Node* p){
// Node* righty=p;
// while(righty->right!=NULL)
// righty=righty->right;
// return righty;
//}
void BST::inorder(Node* p){
if(p!=NULL){
inorder(p->left);
cout<<p->info<<" ";
inorder(p->right); }
}
void BST::inorderTraversal(){
cout<<endl<<"Inorder: ";
inorder(root);
cout<<endl;
}
//to print tree hightwise i.e. all nodes at h1, then all nodes at h2, then at h3
void BST::custom_print(){
//Node* temp;
if(root==NULL)
return;
queue<Node*> Q;
Q.push(root);
//Q.push(NULL);
while(!Q.empty()){
curr=Q.front();
cout<<curr<<" ";
Q.pop();
Q.push(curr->left);
Q.push(curr->right);
}
}
int BST::countLeaves(Node *T)
{
if(T ==NULL) //if T is empty, return0
{
return(0);
}
else if(T -> left == NULL && T-> right == NULL) //if T has0 children, then it is a leaf
{
return(1);
}
else
{
return countLeaves(T -> left) + countLeaves(T -> right); //recursive call to find more leaves
}
}
Main.cpp
#include<iostream>
#include "BSTFunction.hpp"
int main()
{
BST leaves;
leaves.insert(24);
leaves.insert(43); //The code will take all of these numbers entered into the main function and put them in traversal order, much like it could under any order (post or pre) if needed. (Note to self: Not needed for this assignment)
leaves.insert(82);
leaves.insert(22);
leaves.insert(12);
leaves.insert(92);
leaves.insert(68);
leaves.insert(20);
leaves.insert(4);
cout << "These are the in order leaves for the Bianary Search Tree. " << endl;
leaves.inorderTraversal();
cout << "The number of leaves are: " << endl;
leaves.countLeaves()
//leaves.custom_print();
return 0;
}
The problem in your code is that you have an argument in your countLeaves() function-
int BST::countLeaves(Node *T)
When you call this function from your main, it doesn't have an
argument to give to countLeaves(). It throws an error as it doesn't
receive any parameter.
As for the solution, you'll have to create a Node object in your main and send it as an argument. You'll have to worry about what and how you are going to do all this. There seems to be a few errors both in logic and syntax. (I commented your countLeaves() call and it threw many errors.
Recommend using debugger.
Try to print values and "Function entered" print statements to make it easier to find mistakes in your program if you cannot use debugger at the moment.
Hope this was helpful.

sum of left leaf nodes in a binary tree

This solution shows me segmentation fault, though it works fine for all the trees I tried. can anyone please help me detect the error.
code:
/*Structure of the node of the binary tree is as
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
*/
// function should return the sum of all
// left leaf nodes
int sum=0,i=1;
Node* h;
int leftLeafSum(Node* root)
{
if(i==1)
{
h=root;
i--;
}
Node* temp=root;
if((temp->left!=NULL)&&(temp->left->left==NULL)&& (temp->left->right==NULL))
sum+=temp->left->data;
if(temp->left!=NULL)
leftLeafSum(temp->left);
if(temp->right!=NULL)
leftLeafSum(temp->right);
if(temp==h)
{
i=1;
int s=sum;
sum=0;
return s;
}
}
You need to check that the initial pointer is not equal to NULL:
int leftLeafSum(Node* root)
{
if (root==NULL)
return 0;
...
When I add this in, the website accepts the submission as being correct.

Rebuild a binary tree from pre--order and min-order transverse sequence, error in re-build procedure

The input is preOrder:BCAD and midOrder: CBAD, but there is error in the recursive build function. If my guess is right, the while body can't jump out due to certain error, but I have no idea what the error exactly is.
#include <iostream>
using namespace std;
struct Node
{
char data;
Node* left;
Node* right;
Node(char d=0, Node* l=NULL, Node* r=NULL):data(d),left(l),right(r) {}
};
void recoverTree(char* pre, char* mid, Node* root);
void postTranverse(Node* root);
void clean(Node* root);
int main()
{
char preArr[27], midArr[27];
while(cin>>preArr>>midArr)
{
Node* root;
recoverTree(preArr,midArr,root);
postTranverse(root);
clean(root);
}
return 0;
}
void recoverTree(char* pre, char* mid, Node* root)//build binary tree from given sequence
{
char* midTemp=mid;
if(*mid==0)
{
root=NULL;
return;
}
while(true) //loop can't jump out
{
if(*pre==*midTemp)
{
root=new Node(*pre);
*midTemp=0; //how to mark to stop the recursion, wrong?
break;
}
++midTemp;
}
recoverTree(pre+1,mid,root->left);
recoverTree(pre+1,midTemp+1,root->right);
}
void postTranverse(Node* root)// post tranverse the tree
{
if(root==NULL)
return;
//if(root->left!=NULL)
postTranverse(root->left);
//if(root->right!=NULL)
postTranverse(root->right);
cout<<root->data;
}
void clean(Node* root) //release memory in heap
{
if(root->left!=NULL)
clean(root->left);
if(root->right!=NULL)
clean(root->right);
delete root;
}

Construction of Binary Search Tree from preorder traversal iteratively (not recursion)

The following is the code to converted a preorder traversal of a Binary Search Tree to the original tree.
The following code takes an array of integers, which represent the pre order traversal of a a Binary search tree. The root of the construct tree is returned.
struct Node* constructTree(int pre[], int size)
{
stack<struct Node* > s;
int i;
struct Node* root=newNode(pre[0]);
struct Node* temp;
struct Node* top_node;
s.push(root);
for(i=1;i<size;i++)
{
temp=NULL;
while(!s.empty()&&pre[i]>(s.top()->data))
{
temp=s.top();
s.pop();
}
if(temp==NULL)
{
top_node=s.top();
top_node->left=newNode(pre[i]);
s.push(top_node->left);
}else
{
temp->right=newNode(pre[i]);
s.push(temp->right);
}
}
return root;
}
Source: http://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/
I have trouble understanding this code. Can anybody help me understand the following:
At any given iteration, what values are stored in the stack, in relation to the current value being pointed out by pre[i]
Is there any other iterative method for constructing a BST from a given preorder traversal?
Thank you.
After the iteration where the node containing pre[i] is constructed, the stack contains that node on top, under which its leafmost to rootmost ancestors with exactly one child are stored top to bottom.
Check if this works:
public:
TreeNode* bstFromPreorder(vector<int>& preorder) {
TreeNode *root = new TreeNode(preorder[0]);
stack<TreeNode*> nodes;
nodes.push(root);
for (int i = 1; i < preorder.size(); i++) {
TreeNode *temp = new TreeNode(preorder[i]);
if (temp->val < nodes.top()->val)
nodes.top()->left = temp;
else {
TreeNode *prev;
while (!nodes.empty() && nodes.top()->val < temp->val) {
prev = nodes.top();
nodes.pop();
}
prev->right = temp;
}
nodes.push(temp);
}
return root;
}

Why isn't my printLevel function working?

I have written this code to do level order traversal of Binary Search tree. Error is only in printLevel function because all other functions are working fine.
#include <queue>
using namespace std;
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data){
struct node* node = new (struct node);
node->data=data;
node->left=NULL;
node->right=NULL;
return (node);
};
struct node* insert (struct node* node, int data){
if (node==NULL){
return (newNode(data));
}
else {
if (data<=node->data) node-> left=insert(node->left,data);
else node->right=insert(node->right,data);
return (node);
}
}
void printLevel(struct node* node){
queue<struct node*> q;
while(node!=NULL){
cout << node->data << " ";
q.push(node->left);
q.push(node->right);
node=q.front();
}
}
int main(){
int n;
cin >>n;
int m;
cin >>m;
struct node* root=newNode(m);
for (int i=0;i<n-1;i++){
cin>>m;
insert(root,m);
}
printLevel(root);
// printPostOrder(root);
// cout <<maxDepth(root);
// debug(maxDepth(root), minValue(root), printTree(root));
//struct node* root=build123();
}
Here is the algorithm: (http://www.geeksforgeeks.org/level-order-tree-traversal/)
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root /start from root/
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from q and assign it’s value to temp_node
I am taking input 3,1,4,2,7,6,5 for 7 nodes. It gets stuck in infinite loop. I have also implemented following two functions based on another method and it is working fine:
void levelOrder(struct node* node, int level ){
if (node==NULL){
return;
}
if (level==1){
cout << node->data;
}
else if (level>1){
levelOrder(node->left,level-1);
levelOrder(node->right,level-1);
}
}
void printLevelOrder(struct node* root){
for (int i=1;i<=maxDepth(root);i++){
levelOrder(root,i);
}
}
It is O(n^2) but above one is O(n). What's wrong with my code? Thanks.
I suspect that your loop termination is wrong.
Instead of node != NULL, you should check to see if !q.empty().
Also, the call q.front does not remove the element from the queue; to do that, you need pop (after calling front).
This code works for me:
void printLevel(struct node* node){
std::queue<struct node*> q;
q.push(node);
while(!q.empty()) {
node=q.front();
q.pop();
if ( node != NULL ) {
std::cout << node->data << " ";
q.push(node->left);
q.push(node->right);
}
}
}