标签:树的遍历 lse while pytho == int 中序遍历 实战 turn
class TreeNode:
def __init__(self,val,left=None,right=None):
self.val=val
self.left=left
self.right=right
t7 = TreeNode(7)
t6 = TreeNode(6)
t5 = TreeNode(5)
t4 = TreeNode(4)
t3 = TreeNode(3,t6,t7)
t2 = TreeNode(2,t4,t5)
t1 = TreeNode(1,t2,t3)
res = []
def pre_order(root):
global res
if not root:
return
res.append(root.val)
pre_order(root.left)
pre_order(root.right)
pre_order(t1)
print("先序遍历:", res)
res = []
def in_order(root):
global res
if not root:
return
in_order(root.left)
res.append(root.val)
in_order(root.right)
in_order(t1)
print("中序遍历:", res)
res = []
def post_order(root):
global res
if not root:
return
post_order(root.left)
post_order(root.right)
res.append(root.val)
post_order(t1)
print("后序遍历:", res)
def level_order(root):
def helper(root, lev):
if not root:
return
else:
sol[lev-1].append(root.val)
if len(sol) == lev:
sol.append([])
helper(root.left,lev + 1)
helper(root.right, lev + 1)
sol = [[]]
helper(root, 1)
return sol[:-1]
res = level_order(t1)
print("层次遍历:", res)
结果:
先序遍历: [1, 2, 4, 5, 3, 6, 7]
中序遍历: [4, 2, 5, 1, 6, 3, 7]
后序遍历: [4, 5, 2, 6, 7, 3, 1]
层次遍历: [[1], [2, 3], [4, 5, 6, 7]]
def pre_non_recursive_order(root):
if not root:
return []
res = []
stack = []
while stack or root:
while root:
res.append(root.val)
stack.append(root)
root = root.left
if stack:
tmp = stack.pop()
root = tmp.right
return res
res = pre_non_recursive_order(t1)
print("先序遍历:", res)
def in_non_recursive_order(root):
if not root:
return []
res = []
stack = []
while stack or root:
while root:
stack.append(root)
root = root.left
if stack:
tmp = stack.pop()
res.append(tmp.val)
root = tmp.right
return res
res = in_non_recursive_order(t1)
print("中序遍历:", res)
def post_non_recursive_order(root):
if not root:
return []
res = []
stack1 = [root]
stack2 = []
while stack1:
tmp = stack1.pop()
if tmp.left:
stack1.append(tmp.left)
if tmp.right:
stack1.append(tmp.right)
stack2.append(tmp)
while stack2:
res.append(stack2.pop().val)
return res
res = post_non_recursive_order(t1)
print("后序遍历:", res)
def level_non_recursive_order(root):
if not root:
return [[]]
res = []
queue = [root]
while queue:
tmp = []
for i in range(len(queue)):
t = queue.pop(0)
tmp.append(t.val)
if t.left:
queue.append(t.left)
if t.right:
queue.append(t.right)
res.append(tmp)
return res
res = level_non_recursive_order(t1)
print("层次遍历:", res)
结果:
先序遍历: [1, 2, 4, 5, 3, 6, 7]
中序遍历: [4, 2, 5, 1, 6, 3, 7]
后序遍历: [4, 5, 2, 6, 7, 3, 1]
层次遍历: [[1], [2, 3], [4, 5, 6, 7]]
(1)先序遍历
(2)后序遍历
(1)中序遍历
(2)后序遍历
标签:树的遍历 lse while pytho == int 中序遍历 实战 turn
原文地址:https://www.cnblogs.com/xiximayou/p/14269034.html