-1

I want to return the flag as TRUE if I meet the if condition in my code, which I am unable to do.

class createnode:

    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None

    def traverse(self, root,flag,sum,prev=0):
        if root:
            if root.data + prev==sum:
                print("pairs are",root.data,prev)
                flag=True
                return flag
            self.traverse(root.left,flag,sum,prev=root.data)
            self.traverse(root.right,flag,sum,prev=root.data)
        else:
            return


root = createnode(8)
root.left=createnode(4)
root.right = createnode(10)
root.left.left=createnode(2)
root.left.right=createnode(6)
root.right.left = createnode(9)
root.right.right = createnode(12)
flag=root.traverse(root,flag=False,sum=19)
print(flag)

Output: True

But my output is coming as None. Can someone help me here?

1
  • 2
    You have a return statement that does not return anything - i.e. None. Commented Mar 29, 2020 at 20:39

1 Answer 1

1

Always make sure to return the value you're interested in, in all of the possible execution paths of the recursion. And combine the results of the recursive calls, otherwise you'll loose them!

def traverse(self, root, sum, prev=0):
    if root:
        if root.data + prev == sum:
            print("pairs are", root.data, prev)
            return True
        return self.traverse(root.left, sum, prev=root.data) or \
               self.traverse(root.right, sum, prev=root.data)
    else:
        return False

The result will come out as the returned value of the function, not as a parameter: that wouldn't have worked, you were just assigning a value local to a single execution of the function, it will get lost.

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

2 Comments

Accepted.I have seen return self.traverse(root.left,flag,sum,prev=root.data) or \ self.traverse(root.right,flag,sum,prev=root.data) statement for the first time. what does it mean? @Oscar
The backslash \ is just a way to break the line and continue in the following. It's the same as return self.traverse(...) or self.traverse(...) in a single line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.