# 树的构造

``````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)
``````

## 非递归-先序遍历

``````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）后序遍历

（1）中序遍历
（2）后序遍历

【刷题】二叉树

(0)
(0)