2017-05-10 3 views
0

leetcode 질문을 연습하고 있으며 변수를 업데이트하는 데 문제가 있습니다. 내 참조를 올바르게 전달하지 않을 것 같습니다. 대답은 3이 될 것으로 기대하지만 1을 얻고 있습니다. 코드를 실행하고 대답 3이 달성되었지만 다시 돌아와서 1을 얻습니다.Python에서 참조로 변수 전달

목표는 가장 길게 찾습니다. 이진 트리에서 노드의 연속적인 체인.

예 :

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)) 
+4

문제와 관련된 모든 관련없는 논리를 전혀 사용하지 않고 최소한의 문제를 생성하면 더 빠르고 더 빨리 답변을 얻을 수 있습니다. DFS 구현에 대해 확신이 서지 않으면 별도의 질문으로 게시하십시오. – slezica

+4

Python에서 참조로 변수를 전달할 수 없습니다. 실제로 변수를 전혀 전달하지 않습니다. 객체를 전달할 수 있습니다. – user2357112

+1

기술적으로, 파이썬은 참조에 의한 전달 의미를 지원하지 않습니다. –

답변

2

귀하의 문제는이 c의 값입니다 저장되지 않습니다. 재귀 호출 중에 c의 값은 3으로 올바르게 설정됩니다. 그러나 제어 흐름이 순환 스택 위로 이동하기 시작하면 c 값이 손실됩니다. 이 문제를 해결하려면 c의 속성을 Solutions으로 만들 수 있습니다. 이렇게하면 재귀 호출을 통해 c의 값을 저장할 수 있습니다.

3 
3

당신은 longestConsecutive 방법에서 count를 반환하지만 아무것도에 할당하지 않을 : 출력을 가지고

def longestConsecutive(self, root, count=0): 
     """ 
     :type root: TreeNode 
     :rtype: int 
     """ 
     self.c = count # make c an attribute of Solution. 
     if root: 
      self.c = max(self.c, self.DFS(root)) 
      self.longestConsecutive(root.left, self.c) 
      self.longestConsecutive(root.right, self.c) 
     return self.c 

. 대신 다음을 시도해보십시오.

def longestConsecutive(self, root, count=0): 
    """ 
    :type root: TreeNode 
    :rtype: int 
    """ 
    c = count 
    if root: 
     c = max(c, self.DFS(root)) 
     c = self.longestConsecutive(root.left, c) 
     c = self.longestConsecutive(root.right, c) 
    return c