How would you insert random int in a binary tree? eg 1,5,34,90,3,56,1. What is the logic behind inserting these nodes?
This is a discussion on Insert elements in binary tree within the C Programming forums, part of the General Programming Boards category; How would you insert random int in a binary tree? eg 1,5,34,90,3,56,1. What is the logic behind inserting these nodes?...
How would you insert random int in a binary tree? eg 1,5,34,90,3,56,1. What is the logic behind inserting these nodes?
http://en.wikipedia.org/wiki/Binary_Tree
It depends upon which type of a binary tree you use. If you want the tree balanced, then the logic is different. If you just want to insert without it being balance, then if you accept the numbers that you gave in that order it would be like this:
- 1 is made the root.
- 5 is greater than 1, so inserted right.
- 34 is greater than 1, so inserted right. 34 is greater than 5, so inserted right.
- 90 is greater than 1, so inserted right. 90 is greater than 5, so inserted right. 90 is greater than 34, so inserted right.
- 3 is greater than 1, so inserted right. 3 is less than 5, so inserted left.
...
And so on and so forth.
Okay...it looks like a Binary search tree insertr. I wasn't sure if binary tree follows the same procedure. Thanks!
A binary tree just means that internal nodes never have more than two children. But a tree isn't much use unless it has SOME kind of ordering to it. You're right to make the distinction, because there is more than one possible useful order.
A binary search tree is one order, which MacGyver described. A heap is another possible order. And there are things like binary Huffman trees where the order is actually a clever way of encoding information.
So to answer your general question, you insert data in a binary tree by deciding where to insert it and then inserting it there To get a more specific answer you have to ask a more specific question.