class TreeNode:node
def __init__(self, value=None, left=None, right=None): self.value = value self.left = left # 左子樹 self.right = right # 右子樹
node1 = TreeNode("A",app
TreeNode("B", TreeNode("D"), TreeNode("E") ), TreeNode("C", TreeNode("F"), TreeNode("G") ) )
def preTraverse(root):code
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):it
if root is None: return afterTraverse(root.left) afterTraverse(root.right) print(root.value)
def dfs(root):class
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)while