1. 首页
  2. IT资讯

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

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)

本文来自投稿,不代表程序员编程网立场,如若转载,请注明出处:http://www.cxybcw.com/200422.html

联系我们

13687733322

在线咨询:点击这里给我发消息

邮件:1877088071@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

QR code