Binary Tree Deserialization

So as a learning exercise, I am trying to read and write a binary tree to a file. After googling around, I decided to use a preorder traversal (including null nodes) to write the binary tree to the file. I got stuck trying to read a tree from a file. I can't figure out how to create an unknown number of nodes when they are needed. I could use an array, but that just seems bulky - plus it could run out of space. Is that what I have to do? I've heard of vectors before, but not very much. Are they more appropriate for this situation?

Thanks,
Numeri
Can't you create the nodes when you need them, while traversing?
Sorry for being unclear - that's exactly my problem - I don't know how. What would I 'name' each node?

Thanks!
Numeri
Last edited on
name? Do they need a name? I was thinking you could create the nodes with new.
I just read about the new operator here: http://www.cplusplus.com/reference/new/operator%20new/ . Based on it, I think I should do this.
1
2
3
4
5
//...
new (curNode.lChild) node;
//...
curNode = *curNode.lChild;
//... 


Would that work? (Sorry, I've just started learning about pointers recently.)

Thank you,
Numeri
Last edited on
Another question, really quick, why is this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
string wBinTree(node *p)
{
	string str = "";
	if (!p)
	{
		str += "# ";
	}
	else
	{
		str += p->data + " ";
		str += (wBinTree(p->lChild)+wBinTree(p->rChild));
		return str;
	}
}

giving me this error:
Unhandled exception at 0x75f3c41f in ... std::length_error at memory location 0x0025ef04..


I'm compiling with Visual Studio 2010.

Thanks,
Numeri

EDIT:
I'm an idiot, sorry. I accidently put the return inside the else statement.
Last edited on
Topic archived. No new replies allowed.