Tree functions.

I tried to make a tree function based on a binary tree tutorial online.
This is my version and their version

(theirs)
struct node
{
int key_value;
node *left;
node *right;
};
(mine)
template<class T>
struct node
{
T key_value;
vector<*node>;

};

i am not too sure how to do tree traversal
Assuming this is a binary tree. The best way to do binary tree traverals is through recursion. If you have a function that starts at the root, to traverse a tree you just have three things to do:

1. Look at current node
2. Go left
3. Go right

Assuming you want to implement all three types of traversals (pre-order, in-order, post-order) the great thing with recursion is that they all have the same lines, just in a different order. Let's say you want to display the tree, here's the psuedocode for each:

Pre-Order:
Display Current Node
While left child exists, Pre-Order(left child)
While right child exists, Pre-Order(right child)

In-Order:
While left child exists, In-Order(left child)
Display Current Node
While right child exists, In-Order(right child)

Post-Order:
While left child exists, Post-Order(left child)
While right child exists, Post-Order(right child)
Display Current Node

Let me ask you a question. If you are making a binary tree, is there a reason why you are using a vector for the nodes? Binary trees, by definition, only have at most two children for each node. There's not really a reason to use a vector unless it's going to be an n-nary tree where each node can have between 0 and n number of nodes. That is, unless you are planning on reusing the node for other trees where you will have a chance of having n nodes.
Of course i am trying to make a n-nary tree . (DUH!!!)
Topic archived. No new replies allowed.