Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Duyệt Inorder cây nhị phân trong Python


Giả sử chúng ta có một cây nhị phân. Chúng ta phải duyệt cây này theo sơ đồ inorder (trái - gốc - phải) mà không dùng đệ quy. Ví dụ cây như sau:

Duyệt Inorder cây nhị phân trong Python

Thứ tự duyệt sẽ là [2,5,7,10,15,20].

Các bước thực hiện

  • Tạo hai mảng res và stack, đặt curr := root.
  • Chạy vòng lặp vô hạn:
    • Khi current không phải None:
      • Đẩy curr vào ngăn xếp, đặt curr := left của curr.
    • Khi độ dài ngăn xếp = 0, trả về res.
    • node := phần tử lấy ra khỏi ngăn xếp.
    • Thêm giá trị của node vào res.
    • curr := right của node.

Ví dụ

Xem triển khai sau để hiểu rõ hơn:

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

def insert(temp, data):
    que = []
    que.append(temp)
    while len(que):
        temp = que[0]
        que.pop(0)
        if not temp.left:
            temp.left = TreeNode(data)
            break
        else:
            que.append(temp.left)
        if not temp.right:
            temp.right = TreeNode(data)
            break
        else:
            que.append(temp.right)

def make_tree(elements):
    Tree = TreeNode(elements[0])
    for element in elements[1:]:
        insert(Tree, element)
    return Tree

class Solution(object):
    def inorderTraversal(self, root):
        res, stack = [], []
        current = root
        while True:
            while current:
                stack.append(current)
                current = current.left
            if len(stack) == 0:
                return res
            node = stack[-1]
            stack.pop(len(stack)-1)
            if node.data is not None:
                res.append(node.data)
            current = node.right
        return res

ob1 = Solution()
root = make_tree([10,5,15,2,7,None,20])
print(ob1.inorderTraversal(root))

Đầu vào

[10,5,15,2,7,null,20]

Đầu ra

[2,5,7,10,15,20]