二叉樹的遍歷真的是編了忘忘了編,直接Mark到這邊以便查閱。
樹的相關知識:👉
堆的相關知識:👉數據結構:堆(Heap)
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
a = TreeNode(10)
a.left = TreeNode(6)
a.right = TreeNode(13)
a.left.left = TreeNode(4)
a.left.right = TreeNode(8)
a.right.left = TreeNode(0)
a.right.right = TreeNode(16)
a.right.left.left = TreeNode(1)
深度優先
前序遍歷:先根再左後右DLR
def DSFbyRecurrentDLR(ListPrint,root): #(root)
if root is not None:
#print(root.val)
ListPrint.append(root.val)
if root.left is not None:
DSFbyRecurrentDLR(ListPrint, root.left)
pass
if root.right is not None:
DSFbyRecurrentDLR(ListPrint, root.right)
pass
def testDSFbyRecurrentDLR(root):
k = []
DSFbyRecurrentDLR(k, root)
print(k)
testDSFbyRecurrentDLR(a)
def DSFbyStackDLR(root):
if root is not None:
stack = []
stack.append(root)
while len(stack) :
cur_node = stack.pop()
print(cur_node.val)
if cur_node.right is not None:
stack.append(cur_node.right)
if cur_node.left is not None:
stack.append(cur_node.left)
DSFbyStackDLR(a)
輸出:[10, 6, 4, 8, 13, 0, 1, 16]
中序遍歷:先左再根後右 LDR
def DSFbyRecurrentLDR(ListPrint, root): #(root)
if root is not None:
if root.left is not None:
DSFbyRecurrentLDR(ListPrint, root.left)
pass
#print(root.val)
ListPrint.append(root.val)
if root.right is not None:
DSFbyRecurrentLDR(ListPrint, root.right)
pass
def testDSFbyRecurrentLDR(root):
k = []
DSFbyRecurrentLDR(k, root)
print(k)
testDSFbyRecurrentLDR(a)
Warning: 壓中左,彈左,再壓右
def DSFbyStackLDR(root):
if root is not None:
# if the memory path is needed, a stack must be needed
stack = []
cur = root # the scanning cur_p for rootTree
while len(stack) or cur is not None:
while cur is not None:
stack.append(cur)
cur = cur.left
cur = stack.pop()
print(cur.val)
cur = cur.right
中序的非遞歸算法和可以當作回溯法在二叉樹上搜索的應用。
即若節點不存在,則尋找上一級節點。解空間就是樹的val組成的空間,因此沒有限制條件。
輸出: [4, 6, 8, 10, 1, 0, 13, 16]
後續遍歷:先左再右後根 LRD
def DSFbyRecurrentLRD(ListPrint, root): #(root)
if root is not None:
if root.left is not None:
ListPrint.append(DSFbyRecurrentLRD(ListPrint, root.left))
#DSFbyRecurrent(root.left)
pass
if root.right is not None:
ListPrint.append(DSFbyRecurrentLRD(ListPrint, root.right))
# DSFbyRecurrent(root.right)
#print(root.val)
return root.val
def testDSFbyRecurrentLRD(root):
k = []
k.append(DSFbyRecurrentLRD(k, root))
print(k)
testDSFbyRecurrentLRD(a)
Warning: STACK正常彈中壓左右,彈去STACKSAVE,最後STACKSAVE彈出
def DSFbyStackLRD(root):
if root is not None:
stack = []
stack.append(root)
stackSave = []
#多用一個stackSave來承載
while len(stack):
cur_node = stack.pop()
stackSave.append(cur_node)
if cur_node.left is not None:
stack.append(cur_node.left)
if cur_node.right is not None:
stack.append(cur_node.right)
# print(stack)
while len(stackSave):
k = stackSave.pop().val
print(k)
# DSFbyStackDLR(a)
DSFbyStackLRD(a)
輸出:[4, 8, 6, 1, 0, 16, 13, 10]
廣度優先
使用隊列:前出中壓左右