C++ Binary Search Tree preorder printing tree problem

In summary, the program should ask for an input file containing integer keys to be added to the search tree. The file will contain one key per line. Add these keys in the order given in the file to the search tree. Then print the entire tree using preorder traversal i.e., root, left-child, right-child.
  • #1
Faris1985
3
0
Q.When run the program should ask for an input file containing integer keys to be added to the
search tree. The file will contain one key per line. Add these keys in the order given in the file to
the search tree. Then print the entire tree using preorder traversal i.e., root, left-child, right-child.
The output must be indented properly to show the appropriate levels.
For example, if the input keys are 4, 3, 7, 8, 6. The output should look like this
4
<2 spaces>3
<2 spaces>7
<3 spaces>6
<3 spaces>8I have made the tree. How do I go about printing it as shown above?? ANY help would highly be appreciated.
 
Last edited:
Physics news on Phys.org
  • #2
This is my code. Sorry i could not include comments :(
Code:
#include <iostream>
#include <fstream>
#include <istream>
#include <string>
using namespace std;


struct node
{
	int data;
	int depth;
    struct node *left, *right;
};


void insert(struct node *r, struct node *p)
{
    if ((r->right == NULL) && p->data > r->data)
    r->right = p;
    else if ((r->right != NULL) && p->data> r->data)
    insert(r->right, p);
    if ((r->left == NULL) && p->data< r->data)
    r->left = p;
    else if ((r->left != NULL) && p->data< r->data )
    insert(r->left, p);
}
void tree(struct node *r, int c)
{
    int top, flag;
    struct node *w, *stack[20];
    if (r != NULL)
    {
        if (c != 4)
        {
            if (c == 1)
            cout<<r->data<<endl;
			
            tree(r->left, c);
            if (c == 2)
            cout<<r->data<<endl;
            tree(r->right, c);
            if (c == 3)
            cout<<r->data<<endl;
        }
    }
 
}

void main()
{
    int choice, c, i, flag,z,j=1;
    char temp = 'N', temp1[15];
    struct node *s, *root, *r, *q;
    root = NULL;

	string line;
	string v;
	cout<<"Enter an unspaced string of path to the file\n (ALL FOLDER NAMES AS WELL AS FILENAMES MUST NOT CONTAIN SPACES)\n"<<endl;
	cin>>v;
	int a;

	
	
	
	fstream myfile (v);
	if (myfile.is_open()) //if the file is open
	{
		while (! myfile.eof() ) //while the end of file is NOT reached
		{
			getline(myfile,line);
			int TempNumOne=line.size();
			
			
			s = (node*)malloc(sizeof(struct node));
			s->left = NULL;
			s->right = NULL;
			int pp=atoi(line.c_str());
			s->data=pp;

			
			if (root == NULL)
                root = s;
                else
                insert(root, s);
               
		}
	}
		myfile.close(); 
      
			cout<<"\nPreorder\n"<<endl;
			if (root == NULL)
				cout<<("Tree Not Started Yet");
			else
				tree(root, 1);
			j++;
			cout<<("\n Press Any Key To Continue...");
		
}
 
Last edited by a moderator:
  • #3
When you enter code, please surround it with [noparse]
Code:
[/noparse] tags. This makes your code easier to read by preserving your indentation.
 
  • #4
Clean up your insert routine to only test p->data against r->data once.

Think about using the (currently unset) depth variable in nodes to control spaces.
What is the point of "c" in routine "tree"?
 
  • #5


There are a few different approaches you could take to print the tree in preorder traversal with proper indentation. One option is to use recursion, where you start at the root and recursively print the root, then the left child, and then the right child. Each time you print a node, you can add a certain number of spaces (based on the level of the node) before printing the value. You would also need to keep track of the level as you traverse the tree so that you know how many spaces to add.

Another approach is to use a stack to keep track of the nodes as you traverse the tree. You would start by pushing the root node onto the stack, and then repeatedly pop a node off the stack, print its value, and then push its right child and then its left child onto the stack (if they exist). Again, you would need to keep track of the level and add the appropriate number of spaces before printing the value.

Both of these approaches require some understanding of how binary search trees work and how to traverse them. If you are not familiar with these concepts, I would suggest doing some research or consulting with a colleague or mentor who has experience with binary search trees and can guide you through the process. Good luck!
 

1. What is a Binary Search Tree?

A Binary Search Tree (BST) is a data structure in computer science that is used to store data in a hierarchical structure. It is a type of binary tree in which the value of each node is greater than all values in its left sub-tree and less than all values in its right sub-tree.

2. What is Preorder Traversal?

Preorder traversal is a method of visiting each node in a binary tree in a specific order. In this traversal, the root node is visited first, followed by the left subtree and then the right subtree. This process is repeated recursively until all nodes have been visited.

3. How do you print a Binary Search Tree in Preorder?

To print a Binary Search Tree in preorder, we use the preorder traversal method. Starting from the root node, we visit each node in the tree and print its value. Then, we recursively call the function on the left subtree and then on the right subtree.

4. What is the time complexity of printing a Binary Search Tree in Preorder?

The time complexity of printing a Binary Search Tree in preorder is O(n), where n is the number of nodes in the tree. This is because we visit each node in the tree exactly once, making it a linear time operation.

5. Can a Binary Search Tree have duplicate values?

No, a Binary Search Tree cannot have duplicate values. This is because the property of a BST states that the value of each node must be greater than all values in its left sub-tree and less than all values in its right sub-tree. Having duplicate values would violate this property and make the tree invalid.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
9K
  • Programming and Computer Science
Replies
3
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
17
Views
5K
Back
Top