【发布时间】:2017-05-10 20:25:21
【问题描述】:
我正在练习一个 leetcode 问题,但我无法更新我的变量。我认为我没有正确传递我的参考。我期待答案是 3,但我得到 1。我运行了代码并且得到了答案 3,但是当我跳出递归时,我得到 1。
目标是在二叉树中找到最长的连续节点链。
例如:
1
\
3
/ \
2 4
\
5
答案是 3 --> 3,4,5
下面是可运行代码:
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))
【问题讨论】:
-
如果您生成一个问题的最小示例,而没有围绕它的所有不相关的逻辑,您将获得更好更快的答案。如果您不确定自己的 DFS 实施,请将其作为单独的问题发布
-
不能在 Python 中通过引用传递变量。事实上,你根本不会传递变量。你只能传递对象。
-
从技术上讲,Python 不支持传递引用语义。
-
您正在使用
T,一个 int 变量,作为布尔标志。只需使用True和False。 -
@user2357112 您将对象分配给名称
标签: python binary-tree pass-by-reference