0

So I wrote a code which is supposed to get the parent of a given node in a tree. Here is the pseudo code. Starting from the root,

def parent(self, child): 
    if right child exists:
        if the right child == child:
            return self
        else: self.right.parent(child)
    if left child exists:
        if the left child == child:
            print('f')
            return self
        else: self.left._get_parent(node)

I keep coming across this problem over and over and over again. For the if the left child == child: statement, the function DOES enter the if statement if it finds that either the left child == child or the right child == child.

However, the return statement does not execute this. I know this because when I wrote the if the left child == child: and wrote print('f') after it, it did print f, however, it did not return self. Does anyone know why and can anyone give a solution as to how to fix this problem?

Additionally, does anyone know how to return two statements at once NOT as tuples or lists? For example, if I want to return 1 and 2,

def x(n):
    return 1, 2

This would return (1, 2).. is there any way for it to not return it as a tuple? And just to return it normally. I'm asking this because when it comes to recursion, I want to call the same function on 1 AS WELL AS 2, and not on the tuple (1, 2).

1
  • 1
    1, 2 is a tuple. The parenthesis are syntactic sugar, really. Returning a tuple is the way to return multiple values. Just index the return value or use tuple unpacking. Commented Apr 5, 2013 at 15:36

1 Answer 1

2

Your code discards the return values of recursive calls in the else: branches. You need more return statements:

if right child exists:
    if the right child == child:
        return self
    else: 
        return self.right.parent(child)
if left child exists:
    if the left child == child:
        print('f')
        return self
    else:
        return self.left._get_parent(node)

In Python, the expression 1, 2 creates a tuple, and that is the canonical way to return multiple values from functions. That is how multiple value returns work, by returning a tuple.

Simply unpack the returned value:

def foo():
   return 1, 2

value1, value2 = foo()

or use indexing:

values = foo()
values[0], values[1]
Sign up to request clarification or add additional context in comments.

2 Comments

THE FUNCTION YOU WROTE DOES NOT WORK. IT ONLY RETURNS THE PARENT FOR THE RIGHT CHILD, BUT NOT THE LEFT CHILD.
WHY ARE WE SHOUTING? All I did was add return statements to your code. If your code is not returning the left child, you need to verify your algorithm.

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.