-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?

user7422128
  • 902
  • 4
  • 17
  • 41

1 Answers1

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 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 – user7422128 Mar 29 '20 at 20:45
  • 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. – Óscar López Mar 29 '20 at 20:46