The following python code describes an algorithm for inserting values into a binary search tree .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Using this algorithm, you create a new binary search tree B , and insert the following elements into it in this order :
1 |
|
After these operations, what is the sum of the data in the leaf nodes of B ?
Details and assumptions
A leaf node is a node that has no children (no
left_child
or
right_child
).
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
This solution is not as beautiful as I would like it to be. There is likely a faster, more elegant solution to this, and I will continue to work on that. However, here is the code I have written in Python:
Allow me to explain. First, we define our tree to be the node of the first element in our list - which really makes the first logic statement in binary insert irrelevant. After that, we insert our values into our tree using a for loop. After that, we write a function to recursively test for left and right nodes until they both are equal to None (a leaf node). Then we add the data of that node to a global variable "total sum".
This will create this tree , which you can also make manually if you can't figure out how to write it in code.
Either method will return the answer 3 7