python 二叉樹深度優先搜尋和廣度優先搜尋

傑克曼發表於2019-02-16

class TreeNode:

def __init__(self, value=None, left=None, right=None):
    self.value = value
    self.left = left  # 左子樹
    self.right = right  # 右子樹

node1 = TreeNode(“A”,

             TreeNode("B",
                      TreeNode("D"),
                      TreeNode("E")
                      ),
             TreeNode("C",
                      TreeNode("F"),
                      TreeNode("G")
                      )
             )

def preTraverse(root):

if root is None:
    return
print(root.value)
preTraverse(root.left)
preTraverse(root.right)

def midTraverse(root):

if root is None:
    return
midTraverse(root.left)
print(root.value)
midTraverse(root.right)

def afterTraverse(root):

if root is None:
    return
afterTraverse(root.left)
afterTraverse(root.right)
print(root.value)

def dfs(root):

res = []
if root is None:
    return res
q = []
q.append(root)
while len(q) > 0:
    r = q.pop()
    print(r.value)
    if r.left is not None:
        # 非空左孩子入隊
        q.append(r.left)
    if r.right is not None:
        # 非空右孩子入隊
        q.append(r.right)
    res.append(r.value)
return res

def bfs(root):

# write your code here
res = []
# 如果根節點為空,則返回空列表
if root is None:
    return res
# 模擬一個佇列儲存節點
q = []
# 首先將根節點入隊
q.append(root)
# 列表為空時,迴圈終止
while len(q) > 0:
    length = len(q)
    r = q.pop(0)
    print(r.value)
    if r.left is not None:
        # 非空左孩子入隊
        q.append(r.left)
    if r.right is not None:
        # 非空右孩子入隊
        q.append(r.right)
    res.append(r.value)
return res

dfs(node1)
print(“——————-“)
bfs(node1)

相關文章