0

I have a multi nested tree structure and i am trying to find the current level of the provided string/node.I an using recursion to traverse the nodes and return the current level.

def dicq(self,value,current_level):
    d = {}
    for child in self.children:
       if child.name == value:
        print current_level
       else:
        (child.dicq(value,current_level+1))
    return current_level


root.dicq('7.3',1)

root is the nested tree structure and i am giving it 7.3(The node which i am finding the level of) and 1(the default level meaning first children). If i simply print the current_level in the if statement it is correct but if i put return in the if statement it doesn't return.I want to return the current level as soon as i find the node.Any suggestions?

1 Answer 1

2

Right now your code is returning current_level irrespective of wheather node you are looking for is found or not. What you need to do is to return current_level only if matching node is found. If not, return something which indicates matching node is not found. Also, you need to ensure your results propagates properly across levels of recursion and you stop looking further when a match is found.

Here is code which might help. Note: I have not tested it.

def dicq(self,value,current_level):
    d = {}
    retval = -1
    for child in self.children:
       if child.name == value:
           retval = current_level
       else:
           retval = child.dicq(value,current_level+1)
           if retval != -1:
                break
    return retval

If value is found, that level will be returned. If not, -1 will be returned indicating that its not found anywhere in that part of the tree.

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

1 Comment

Yes thankyou i was going crazy over a simple thing :(

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.