Leaves On A Binary Search Tree

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
class Node:
    def __init__(self, val):
        self.left_child = None
        self.right_child = None
        self.data = val

def binary_insert(tree, val):
    # insert val at root if tree is empty
    if tree is None:
        tree = Node(val)
    else:
        # if val is less than current node, 
        # insert val into left subtree
        if (tree.data > val):
            tree.left_child = binary_insert(tree.left_child, val)
        # else, insert val into right subtree
        else:
            tree.right_child = binary_insert(tree.right_child, val)
    return tree

Using this algorithm, you create a new binary search tree B , and insert the following elements into it in this order :

1
4, 2, 1, 5, 6, 3, 7, 9, 8, 12, 10, 11, 13, 15, 14

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 ).


The answer is 37.

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.

4 solutions

John Fish
Jan 11, 2014

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:

total_sum = 0
class Node:
    def __init__(self, val):
        self.left_child = None
        self.right_child = None
        self.data = val

def binary_insert(tree, val):
    # insert val at root if tree is empty
    if tree is None:
        tree = Node(val)
    else:
        # if val is less than current node, 
        # insert val into left subtree
        if (tree.data > val):
            tree.left_child = binary_insert(tree.left_child, val)
        # else, insert val into right subtree
        else:
            tree.right_child = binary_insert(tree.right_child, val)
    return tree

def leaf_test(tree):
    global total_sum
    if(tree.left_child == None and tree.right_child == None): #leaf nodes will not have a left or right child
        total_sum+=tree.data
    elif(tree.left_child == None and tree.right_child != None):
        leaf_test(tree.right_child)
    elif(tree.right_child == None and tree.left_child != None):
        leaf_test(tree.left_child)
    else:
        leaf_test(tree.left_child)
        leaf_test(tree.right_child)

value_list = [4, 2, 1, 5, 6, 3, 7, 9, 8, 12, 10, 11, 13, 15, 14]
tree=Node(value_list[0])

for i in range(1,len(value_list)):
    binary_insert(tree, value_list[i])

leaf_test(tree)
print(total_sum)

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 37 \boxed{37}

def count(tree):
    # End recursion
    if tree is None:
        return 0
    if tree.left_child is None and tree.right_child is None:
        return tree.data
    # Recursion
    return count(tree.left_child) + count(tree.right_child)
This is my python (recursive) function. Recursion ends if tree is None or if we found leaf node. This works even if we have empty tree (tree is None)

Petr Bartůněk - 7 years, 4 months ago

Another way is to create a function that sums up the leaf nodes.

def count(tree):
    sum = 0;
    if tree.left_child is not None:
        sum = sum + count(tree.left_child)
    if tree.left_child is None:
        if tree.right_child is None:
            sum += tree.data
    if tree.right_child is not None:
        sum += count(tree.right_child)
    return sum

I'm currently novice at Python programming so I'm not certain if I am doing it correctly. The code is tested and working though via codepad

Nikko Duhaylungsod - 7 years, 4 months ago

Log in to reply

This is a good solution. Just a few things with your code, you can use boolean logic ("and" statement) to reduce your two if statements to one, and use += instead of sum=sum+count. Your code would then look like this:

def count(tree):
    sum = 0;
    if tree.left_child is not None:
        sum += count(tree.left_child)
    if tree.left_child is None and tree.right_child is None:
        sum += tree.data
    if tree.right_child is not None:
        sum += count(tree.right_child)
    return sum

John Fish - 7 years, 4 months ago
R Prakash
Jan 13, 2014

Contruct the binary tree as per the algorithm given.

Then, The data in the leaf nodes of binary tree B are 1, 3, 8, 11, 14 (from left to right).

And, so the sum of data in the leaf nodes = 1 + 3 + 8 + 11 +14 = 37

in c++ u can solve it by many method it is also a answer good

navdeep dhiman - 7 years, 3 months ago

im super new about htis binary search tree.. so what is the rule to apply for the number 10, theres 8 and 12 possibly can put it.. OHHH I just figure it out now.. the if else first checks if it is lower... yup.. it connected to 12

Roi Vinson Abrazaldo - 7 years, 2 months ago

4 is the root node,the rest of elements depend on the logic of the binary tree,(every element greater than the node must be appended to the right and to the left if it's lesser)

Bill Bell
Dec 20, 2015

I hate reasoning.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Node:
    def __init__(self, val):
        self.left_child = None
        self.right_child = None
        self.data = val

def binary_insert(tree, val):
    if tree is None:
        tree = Node(val)
    else:
        if (tree.data > val):
            tree.left_child = binary_insert(tree.left_child, val)
        else:
            tree.right_child = binary_insert(tree.right_child, val)
    return tree

values=[4, 2, 1, 5, 6, 3, 7, 9, 8, 12, 10, 11, 13, 15, 14]

tree=None
for value in values:
    tree=binary_insert(tree, value)

total=0
def getTotal(node):
    global total
    if node.left_child:
        getTotal(node.left_child)
    if node.right_child:
        getTotal(node.right_child)
    if not node.left_child and not node.right_child:
        total+=node.data

getTotal(tree)
print total

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...