I am practicing a leetcode question and I am having trouble updating my variable. I think I am not passing my reference correctly. I am expecting the answer to be 3 but I am getting 1. I ran through the code and the answer 3 is achieved but when i jump back out of my recursion I am getting 1.
The goal is the find the longest consecutive chain of nodes in a binary tree.
ex:
1
\
3
/ \
2 4
\
5
Answer would be 3 --> 3,4,5
Below is the runnable code:
class Node(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def DFS(self, root):
count = 0
if root:
count += 1
q = [root]
while q:
n = q.pop()
T = 0
if n.left:
if n.left.val == n.val + 1:
q.append(n.left)
T = 1
if n.right:
if n.right.val == n.val + 1:
q.append(n.right)
T = 1
if T:
count += 1
return count
def longestConsecutive(self, root, count=0):
"""
:type root: TreeNode
:rtype: int
"""
c = count
if root:
c = max(c, self.DFS(root))
self.longestConsecutive(root.left, c)
self.longestConsecutive(root.right, c)
return c
a = Node(1)
b = Node(3)
c = Node(2)
d = Node(4)
e = Node(5)
a.right = b
b.left = c; b.right = d
d.right = e
poop = Solution()
print(poop.longestConsecutive(a))
T, an int variable, as a boolean flag. Just useTrueandFalse.