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)
相关推荐
qingsongzdq 2019-10-24
燕返 2019-07-01
基尔霍夫的猫 2019-06-21
xinxing00 2015-11-01
HTML学堂码匠 2018-02-07
HTML学堂码匠 2017-12-14
campwin 2018-10-22
PHP100 2019-03-28
ScalersTalk成长会 2018-01-25