Click here to Skip to main content
15,666,479 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone!

Here I am with another doubt this time considering data structures.

I was given a homework sorta.

To create a binary search tree with the following values.

5, 4, 3 ,1, 17, 8, 11

I'd post a picture but i don't know how so.. the old fashioned way

The given solution is :

root node is 5
root's left-child is 4
it's left child is 3
and it's left child is 1

then the right subtree

root's right-child is 17
it's left child is 8
and it's rigth child is 11

written other way :

left subtree(5->4, 4->3, 3->1 ) right subtree (5->17, 17->8, 8->11)

My Solution differs a bit...

i made it that way :

left subtree(5->4, 4->3, 3->1) right subtree (5->8, 8->11, 11->17)

My question is :

Since both look as being a valid binary trees I can't really see the difference in
these solutions, therefore, my question.. is my solution also a valid solution to
the given problem.

Thanks in advance

What I have tried:

I can see why is the given solution all right but I don't see a valid reason why mine would be wrong,

Is this thinking correct?
Updated 28-Mar-16 0:59am

1 solution

Both trees are perfectly legal.
Simply, the given solution insert values in the order values are given.
In you solution, the 17 is inserted after all other values.
The given solution comes from 5, 4, 3 ,1, 17, 8, 11.
Your solution comes from 5, 4, 3 ,1, 8, 11, 17.
Are you allowed to reorder values.
Share this answer
Member 12371341 28-Mar-16 7:03am    
I'm glad i's fine, regarding the reordering..
No bounds were written.
Guess I better do them the way they were given, but my solution at least from my point of view seemed a little bit more natural.

Thanks once again!
Patrice T 28-Mar-16 7:21am    
If you want a better solution, try to reorder values to balance the tree.
Member 12371341 28-Mar-16 7:27am    
Isn't my solution also a valid and balanced binary tree?

Given the definition : A tree is balanced if the distance from root to each node is equal or not greater then 1.

I think both of them look balanced.

I know we should try to balance them whenever we can since It allows faster times
at various operations on the tree.
Patrice T 28-Mar-16 7:38am    
Build the tree in this order 5, 3, 4 ,1, 11, 8, 17
You will see what I mean.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900