python 二叉树深度优先搜索和广度优先搜索

Jonderwu 2019-06-28

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)

相关推荐