2013-03-15 5 views
1

가정하자 나는 노드 클래스가 있습니다이진 트리와 링크 된 목록 :

class Node: 

    def __init__(self, data, link=None): 
     self.data = data 
     self.link = link 

class BTNode: 

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

내가 이진 검색 트리의 중위 순회의 연결리스트를 만들려고합니다.

내가 지금까지있는 것은 :

테스트 :

UnboundLocalError : 나는 오류 얻을 그러나

if __name__ == '__main__': 
    a1 = BTNode('A') 
    a2 = BTNode('B') 
    a3 = BTNode('C') 
    a4 = BTNode('D') 
    a5 = BTNode('G') 
    a6 = BTNode('E') 
    a7 = BTNode('F') 
    a1.left = a2 
    a1.right = a3 
    a2.right = a4 
    a4.left = a5 
    a3.left = a6 
    a3.right = a7 
    x = inorder(a1) 

지역 변수를 할당하기 전에 참조 'left_head'

대신에 다음과 같이 입력하십시오 :

def _inorder(root): 

    if root is None: 
     return None, None 

    else: 
     temp = Node(root.item) 
     #if root.left: 
     left_head, left_tail = _inorder(root.left) 
     left_tail.link = temp 
     #if root.right: 
     right_head, right_tail = _inorder(root.right) 
     temp.link = right_head 

     return left_head, right_tail 

그러면 오류가 발생합니다. NoneType '객체의 속성'링크가 없습니다. 내 논리가 옳다고 생각하기 때문에 누구나 문제를 볼 수 있습니까? 첫 번째 경우에

답변

0

: 당신이 IFS 중 하나를 입력하지 않으면

if root.left: 
     left_head, left_tail = _inorder(root.left) 
     left_tail.link = temp 
    if root.right: 
     right_head, right_tail = _inorder(root.right) 
     temp.link = right_head 

    return left_head, right_tail 

는, 당신은 left_head도 right_tail을 할당되지 않았을 것입니다.

번째 오류 때문에 첫 번째 검사입니다 :이 임무를

if root is None: 
    return None, None 

:

left_head, left_tail = _inorder(root.left) 

모두 left_head을하고 아무도 없을 left_tail. 그러면 다음 줄에 폭발이 일어납니다.

+0

그래서 어떻게 고칠 수 있습니까? –

+0

글쎄, 자식이없는 노드에 대한 _inorder 호출의 반환 값을 확인하거나 _inorder (node.left)를 호출하기 전에 node.left! = None을 확인하십시오. 권리와 동일합니다. 나는 너에게 그것을 너 자신 시도하고 발견하는 것이 좋습니다. – Mariano