Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a binary tree

I did'nt mean binary search tree.

for example, if I insert values 1,2,3,4,5 in to a binary search tree the inorder traversal will give 1,2,3,4,5 as output.

but if I insert the same values in to a binary tree, the inorder traversal should give 4,2,5,1,3 as output.

Binary tree can be created using dynamic arrays in which for each element in index n, 2n+1 and 2n+2 represents its left and right childs respectively.

so representation and level order traversal is very easy here.

but I think, in-order,post-order,pre-order is difficult.

my question is how can we create a binary tree like a binary search tree. ie. have a tree class which contains data, left and right pointers instead of arrays. so that we can recursively do traversal.

like image 955
Tom Avatar asked May 06 '09 07:05

Tom


2 Answers

If I understand you correctly, you want to create a binary tree from an array

int[] values = new int[] {1, 2, 3, 4, 5};
BinaryTree tree = new BinaryTree(values);

this should prepopulate the binary tree with the values 1 - 5 as follows:

    1
   / \
  2   3
 / \
4   5

this can be done using the following class:

class BinaryTree
{
    int value;
    BinaryTree left;
    BinaryTree right;

    public BinaryTree(int[] values) : this(values, 0) {}

    BinaryTree(int[] values, int index)
    {
        Load(this, values, index);
    }

    void Load(BinaryTree tree, int[] values, int index)
    {
        this.value = values[index];
        if (index * 2 + 1 < values.Length)
        {
            this.left = new BinaryTree(values, index * 2 + 1);
        }
        if (index * 2 + 2 < values.Length)
        {
            this.right = new BinaryTree(values, index * 2 + 2);
        }
    }
}
like image 193
Patrick McDonald Avatar answered Oct 06 '22 00:10

Patrick McDonald


The tree class declaration part is, certainly, not the difficulty here. You basically stated exactly how to declare it, in the question:

class BinaryTree
{
private:
    int data;
    BinaryTree *left, *right;
};

This supports various forms of traversal, like so:

void Inorder(const BinaryTree *root)
{
  if(root == 0)
    return;
  Inorder(root->left);
  printf("now at %d\n", root->data);
  Inorder(root->right);
}

You should be able to deduce pre- and post-order traversals from that. In a real implementation, the tree would probably be templated to store random data, the traversal routines would be more general (with a user-data input, or perhaps user-supplied per-node callback, or whatever), of course.

like image 30
unwind Avatar answered Oct 06 '22 01:10

unwind