Hello, I am having trouble with setting up a program to output the data values along a binary tree below a starting at a user defined point on the tree.
The tree has the root at 5 and the tree is the numbers 2-8.
If I want to start at 5, it will print everything but 5.
6 should output 7 and 8.
4 should output 3 and 2. etc.
I would think that some modification of an Inorder output would be the correct choice, but if it is I am unsure of the way to modify it.
#include<iostream>
//tree should look like:
// 5
// / \
// 4 6
// / \
// 3 7
// / \
// 2 8
usingnamespace std;
struct Node{
int data;
Node *left;
Node *right;
Node *parent;
};
void Inorder(Node *root) {
if (root == NULL) return;
Inorder(root->left); //Visit left subtree
cout << root->data << " ";//Print data
Inorder(root->right); // Visit right subtree
}
Node* GetNewNode(int data){
Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = NULL; //create empty branches
return newNode;
}
Node* insert(Node* root, int data){
if (root == NULL) { //runs when tree is empty
root = GetNewNode(data);
}
elseif (data <= root->data){//will run when the next point has a lower value than the last
root->left = insert(root->left, data);
}
else{//will run when the next point has a higher value than the last
root->right = insert(root->right, data);
}
return root;
}
int main(){
int id;
Node* root = NULL;
root = insert(root, 5); //root node of the tree
for (int x = 4; x > 1; x--){
root = insert(root, x);
}
for (int x = 6; x < 9; x++){
root = insert(root, x);
}
cout << "Enter the value: ";
cin >> id;
Inorder(root); //I'm not sure how to implement the id into this.
return 0;
}
This code allows me to print out the values in order, but how can I edit the Inorder function (or some other function) to print out everything staring from the point given by id in the tree? I have a feeling the solution is simple but I cannot put my finger on it.
(If the question is not clear enough ask what you need to know)
Thank you. That is about half the problem solved, but I am still unsure of the way to start looking through the tree from a user defined point.
How would I change the node that I pass into allBut, so I can print parts of the tree instead of the whole thing? (Pass the node for 3 into allBut to get 2, but how do I select node 3?)