0

I want to test the total depth of a binary tree, so I wrote the following code:


    def nodeDepths(root):
        return depthSum(root, 0)
        
    def depthSum(node, depth)
        if node.left:
            depth += depthSum(root.left, depth+1)
        if node.right:
            depth += depthSum(root.right, depth+1)
        return depth
        
    # This is the class of the input binary tree.
    class BinaryTree:
        def __init__(self, value):
            self.value = value
            self.left = None
            self.right = None

I then encountered the following error, please let me know how to fix this.

Traceback (most recent call last): File "main.py", line 7, in import json_wrapper File "/tester/json_wrapper.py", line 3, in import program File "/tester/program.py", line 4 def depthSum(node, depth) ^ SyntaxError: invalid syntax exit status 1

1 Answer 1

0

Well first off, read the error :P. You have a syntax error on line 4 and your missing a : on the end of your def.

As for your algorithm, not really sure why you have the nodeDepths function, it's not really helping.

For your depthSum function, right off the bat, your algorithm will never complete as you are stuck in an infinite recursive loop - you never actually traverse the tree due to using root instead of node in your depthSum function.

Take a look at this, it's a simple way to check the depth:

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

and just call it directly, with

traverse(root)

I don't see a use case for the nodeDepths function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.