두 갈래 나무의 앞차례, 중차례, 뒷차례 반복(귀속)

1963 단어
두 갈래 나무를 옮겨다니며 귀속법 Python 3 실현:
#  

#  
class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
        self.parent = None

""" 
          0
      /       \
     1          2
   /   \       /  \
  3     4     5    6
"""

#    - -  0 1 3 4 2 5 6
def recursive_preorder_traversal(root):
    if root != None:

        #  
        print(root.data)

        #  
        left = root.left
        if left != None:
            recursive_preorder_traversal(left)

        #  
        right = root.right
        if root.right != None:
            recursive_preorder_traversal(right)

#    - -  3 1 4 0 5 2 6
def recursive_inorder_traversal(root):
    if root != None:

        #  
        left = root.left
        if left != None:
            recursive_inorder_traversal(left)

        #  
        print(root.data)

        #  
        right = root.right
        if right != None:
            recursive_inorder_traversal(right)

#    - -  3 4 1 5 6 2 0
def recursive_postorder_traversal(root):
    if root != None:

        #  
        left = root.left
        if left != None:
            recursive_postorder_traversal(left)

        #  
        right = root.right
        if right != None:
            recursive_postorder_traversal(right)

        #  
        print(root.data)

if __name__ == '__main__':

#  
    root = Node(0)
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node5 = Node(5)
    node6 = Node(6)

    root.left = node1
    node1.parent = root
    root.right = node2
    node2.parent = root
    node1.left = node3
    node3.parent = node1
    node1.right = node4
    node4.parent = node1
    node2.left = node5
    node5.parent = node2
    node2.right = node6
    node6.parent = node2

    recursive_preorder_traversal(root)
    recursive_inorder_traversal(root)
    recursive_postorder_traversal(root)

좋은 웹페이지 즐겨찾기