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.
Related
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.
The code that I tried to print all root to leaf paths in a Binary Tree.
#include<iostream>
#include<stack>
using namespace std;
bool visited[100];
void intilize(){
for(int i=0;i<100;i++)
visited[i]=false;
}
struct node
{
int data;
struct node *left,*right;
};
struct node* createNode(int k)
{
struct node* temp = new node;
temp->left = NULL;
temp->right = NULL;
temp->data = k;
return temp;
}
stack<node*> s,s1;
void print(){
while(!s.empty()){
s1.push(s.top());
s.pop();
}
while(!s1.empty()){
struct node* a= s1.top();
cout<<a->data<<" ";
s1.pop();
s.push(a);
if(s1.empty())
return;
}
}
void printpath(struct node* node){
if(node==NULL) return;
s.push(node);
while(!s.empty()){
struct node* top=s.top();
visited[top->data]=true;
if(top->left!=NULL&&visited[top->left->data]==false)
printpath(top->left);
else if(top->right!=NULL&&visited[top->right->data]==false)
printpath(top->right);
else if(top->left==NULL&&top->right==NULL){
print();
cout<<"\n";
}
s.pop();
}
}
int main() {
struct node* root = createNode(50);
root->left = createNode(7);
root->right = createNode(2);
root->right->left = createNode(1);
root->right->right = createNode(30);
root->right->right->right = createNode(40);
root->right->left->left = createNode(10);
root->right->left->left->left = createNode(12);
intilize();
printpath(root);
return 0;
}
The code gives segmentation fault because there is some issue with the termination condition.
Can someone help me in figuring out the problem.
That approach is over-complicated, and fragile.
A separate stack is not needed for this.
The separate "visible" array is not needed for this.
All that's needed is a stock recursive visitor that recursively descends into this tree, that also takes an additional parameter to a structure that's dynamically built on the stack, which builds the path to the root on the fly, using a link list that goes something like this:
struct path_to_root {
struct path_to_root *next;
struct node *n;
};
Now, all that's needed to print a path to each leaf note is a bog-standard visitor, that recursively iterates over the tree, and this additional parameter. Here's a rough idea of the general approach:
void printpath(struct node *n, struct path_to_root *p)
{
struct path_to_root pnext;
if (!n)
return;
if (!n->left && !n->right)
{
/* Your homework assignment here is to print the path that's in "p" */
}
pnext.n=n;
pnext.next=p;
printpath(n->left, &pnext);
printpath(n->right, &pnext);
}
And this would be invoked as:
printpath(root, NULL);
Your homework assignment, as noted, is to implement the actual code that prints the path to the leaf, using the p parameter, in the space indicated. At that point, the path to the leaf will be found in the p parameter.
Now, one tricky part here is that p will be the leaf's parent, p->next will be its grandparent, and so on. So the path is from the bottom to the top, not top to bottom, but that's a minor detail, that can be handled in the print code.
Or, alternatively, it wouldn't be too much extra work to dynamically build the path to the leaf from top to bottom, in the same manner.
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.
This is my first time working with trees. I wrote a c++ code, but it says Segmentation fault (core dumped) , As far as I searched, this error comes from accessing a memory location that may be NULL. I tried 'new' keyword as malloc() should be avoided in c++, But still I didn't get how to resolve this in my code.
# include<iostream>
using namespace std;
struct node
{
int data;
node *left;
node *right;
}*next;
int k=0;
void tree(int i,/*struct*/ node *next = new node)
{
++k; --i;
if (i==0)
return;
//next = new node;
next->data = k*k;
next->left = NULL;
next->right = NULL;
tree(i, next->left);
tree(i, next->right);
return ;
}
void display (node* next)
{
cout<<next->data<<" ";
if (next->left!=NULL)
{
display(next->left);
display(next->right);
}
}
int main()
{
int h;
cout<<"Enter the expected height of tree : ";
cin>>h;
node *root;
root = new node;
root->data=0;
root->left=NULL;
root->right=NULL;
tree(h, (root->left));
tree(h, (root->right));
cout<<root->data<<" ";
display(root->left);
display(root->right);
return 0;
}
There are serious problems with this code. In particular, here:
void display (node* next)
{
cout<<next->data<<" ";
if (next->left!=NULL)
{
...
}
}
You dereference next without ever checking to see whether it's null. And it will be null. That's enough to explain the error you see.
I say that it will be null because of this:
void tree(int i,/*struct*/ node *next = new node)
{
...
return ;
}
...
root->left=NULL;
...
tree(h, (root->left));
...
display(root->left);
The tree function takes its second argument by value-- that means that it does not change the value of root->left. You then call display with a null argument. I suspect that you think void tree(int i,/*struct*/ node *next = new node) means something other than what it actually means.
More fundamentally, you must review the two ways to pass an argument, by reference and by value.
More fundamentally still, you must start with a small, simple program and build up in small steps, rather than trying to write a big complex program all at once.
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
};
void tree(int i, struct node **root, int k)
{
if (i < 1)
return;
*root = new struct node;
(*root)->data = k*k;
(*root)->left = NULL;
(*root)->right = NULL;
tree(i - 1, &((*root)->left), k + 1);
tree(i - 1, &((*root)->right), k + 1);
}
void display(struct node *root)
{
if (root == NULL)
return;
cout << root->data << " ";
if (root->left != NULL)
display(root->left);
if (root->right != NULL)
display(root->right);
}
int main()
{
struct node *root;
int h;
cout<<"Enter the expected height of tree : ";
cin>>h;
tree(h, &root, 0);
display(root);
return 0;
}
I think you should do some more read up on how pointers works: http://www.tutorialspoint.com/cprogramming/c_pointers.htm
When you where calling tree(h, root->left) you actually just send the pointers value "NULL" == 0x0. As you want to allocate memory for it you should send a reference to the pointer. Hence &root and &((*root)->left). In the display function you have to check for NULL values both for left and right.
The code above is only improved and doesn't handle any freeing of memory, to be able to do that, traverse the tree and use delete on all leafs and work you back to the root.
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;
}