Printing only a certain section of a binary tree

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>

//tree should look like:
//       5
//      / \
//     4   6
//    /     \
//   3       7
//  /         \
// 2           8

using namespace 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);
	}
	else if (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)
Last edited on
1
2
3
4
5
6
7
allBut(Node *node)
{
    if (node) {
        InOrder(node->left);
        InOrder(node->right);
    }
}

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?)
Last edited on
It sounds like you need a find() function to find a node with specific data.
Registered users can post here. Sign in or register to post.