Liondancer
Liondancer

Reputation: 16469

printing max depth in Binary search tree

I am trying to obtain the max depth of a binary search tree however I believe the tree is counting wrong.

my code:

    def BST_maxdepth(root):
        curdepth = [1]
        maxdepth = [1]
        if root is None:
            return -1
        else:
            curdepth[0] = 1
            maxdepth[0] = 1
            if root.left is not None or root.right is not None:
                curdepth[0] += 1
                if curdepth[0] > maxdepth[0]:
                    maxdepth[0] = curdepth[0]
                BST_maxdepth(root.left)
                BST_maxdepth(root.right)
        return maxdepth[0]

classes & BST:

class Node:
    def __init__(self,value):
        self.right = None
        self.left = None
        self.value = value


def BST_Insert(root, node):     # root --> root of tree or subtree!
    if root.value is None:
        root = node             # beginning of tree
    else:
        if root.value > node.value:     # go to left
            if root.left is None:
                root.left = node
            else:
                BST_Insert(root.left, node)

        if root.value < node.value:    # go to right
            if root.right is None:
                root.right = node
            else:
                BST_Insert(root.right, node)

tests:

r = Node(8)


a = Node(5)
b = Node(2)
c = Node(1)
d = Node(3)
e = Node(7)

output:

2

expected output:

4

Upvotes: 0

Views: 3082

Answers (4)

dckrooney
dckrooney

Reputation: 3121

You're not carrying curdepth and maxdepth with you as you recurse, and they're not global. At each call to BST_maxdepth, you declare a new curdepth and maxdepth.

This means that the regardless of how deep your tree is, maxdepth will only ever be 2 (or 1 if the root has no children).

You could try either using an accumulator, or returning a value from each recursive call and building maxdepth that way.

Upvotes: 1

Wayne Werner
Wayne Werner

Reputation: 51817

Why not something like...

def BST_maxdepth(root, depth=0):
    if root is None:
        return depth
    return max(BST_maxdepth(root.left, depth+1),
               BST_maxdepth(root.right, depth+1))

Upvotes: 4

DanGar
DanGar

Reputation: 3078

Your maxdepth from each recursive step is not being passed to the parent step.

The information from

BST_maxdepth(root.left)
BST_maxdepth(root.right)

needs to be returned to the parent.

You are re-instantiating them at each level of the search:

 curdepth = [1]
 maxdepth = [1]

Upvotes: 1

Michael
Michael

Reputation: 2261

You aren't updating maxdepth more than once. Perhaps something like this:

left_depth = BST_maxdepth(root.left)
right_depth = BST_maxdepth(root.right)
maxdepth[0] = max(left_depth, right_depth) + 1

Upvotes: 1

Related Questions