Binary Tree Structure

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
typedef struct node	
	{
		char value; // the character that needs to be compared in the tree
		node *left; // pointers to two children, left and right
		node *right;

	} *nodeptr;

vector <node> v;

	for(int i = 1; i<v.size();i+2){
		if(!v.empty[i]){
		v[2*i] = v[i];
		v.erase[i];
		}
	}
	for(int i = 2; i<v.size();i+2){
		if(!v.empty[i]){
		v[2*i+2] = v[i];
		v.erase[i];
		}
	}


This is a functionality function for a binary tree structure. The function is supposed to add a new root node, and send the previous root node to be the new left child, or right child. In this case, it will be the left child.

1
2
3
4
5
6
7
8
9
10
11
12
13

             a1               
           b2   c3  
         d4 e5  f6 g7
 
             |
             |

                 n1
          a2          -
       b4   c5  
     d8 e9  f10 g11


So, lets say I have my vector that holds like 7 nodes. If i want to insert a new root node, and shove this entire tree to be the left child, will this code work?

Diagram above.

Last edited on
closed account (o3hC5Di1)
Hi there,

I'm no expert on datastructures, but I don't think you need to be switching nodes' places within the vector.
The binary tree is a collection of nodes, each node knows its left or right child.
Hence, it doesn't matter where in the vector the children are, because every node knows its children.

All you need to do is change the children pointers of the nodes. You could probably write a recursive function to do so.

Maybe some of the experts around here could shed their light on this.

All the best,
NwN
Yeah, I was having problems identifying the parent node. I dont actually need a binary tree that throws smaller numbers in the left child, and larger numbers in the right child. I need a binary tree that can read a line input and make its own tree. for example A + B
1
2
3
    + 
A     B


The problem that I was having was connecting the parent node to the children nodes.
Topic archived. No new replies allowed.