二叉树初始化
# Definition for a binary tree node.
class node:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
#示例如何初始化一个二叉树
root = node(5)
root.left = node(7)
root.right = node(8)
root.left.left = node(3)
root.left.right = node(4)
root.left.right.left = node(9)
递归
def preorderTraversal(root, res=[]):
if not root:
return res
res.append(root.val)#根左右
preorderTraversal(root.left, res)
preorderTraversal(root.right, res)
return res
前序遍历递归输出:
print(preorderTraversal(root,res=[]))
[5, 7, 3, 4, 9, 8]
非递归
def preorderTraversal(root):
stack=[]
res=[]
if not root:
return []
while root or stack:
while root:
res.append(root.val)
stack.append(root)
root=root.left#一直遍历到最左边的那个节点
if stack:
temp=stack.pop()
root=temp.right
return res
前序遍历非递归输出:
print(preorderTraversal(root))
[5, 7, 3, 4, 9, 8]
递归
def inorderTraversal(root, res=[]):
if not root:
return res
inorderTraversal(root.left, res)
res.append(root.val)#左根右
inorderTraversal(root.right, res)
return res
中序遍历递归输出:
print(inorderTraversal(root,res=[]))
[3, 7, 9, 4, 5, 8]
非递归
def inorderTraversal(root):
stack=[]
res=[]
if not root:
return []
while root or stack:
while root:
stack.append(root)
root=root.left
if stack:
temp=stack.pop()
root=temp.right
res.append(temp.val)
return res
中序遍历非递归输出:
print(inorderTraversal(root))
[3, 7, 9, 4, 5, 8]
递归
def postorderTraversal(root, res=[]):
if not root:
return res
postorderTraversal(root.left, res)
postorderTraversal(root.right, res)
res.append(root.val)#左右根
return res
后序遍历递归输出:
print(postorderTraversal(root,res=[]))
[3, 9, 4, 7, 8, 5]
非递归
def postorderTraversal(root):
res=[]
if not root:
return res
stack = []
stack.append(root)
while stack:#这里的stack 同时存有节点与节点的值
temp = stack.pop()
if type(temp) is Treenode:#判断当前的值的类型是否是二叉树节点
stack.append(temp.val)
if temp.right:
stack.append(temp.right)
if temp.left:
stack.append(temp.left)
else:#若为节点值则存入
res.append(temp)
return res
后序遍历非递归输出:
print(postorderTraversal(root))
[3, 9, 4, 7, 8, 5]
递归
def levelorder(root):
if not root:
return []
levels=[]
level=0
def helper(level,node):
if level==len(levels):
levels.append([])
levels[level].append(node.val)#按层号遍历
if node.left:
helper(level+1,node.left)
if node.right:
helper(level+1,node.right)
return levels
res=helper(level,root)
return res
层序遍历递归输出:
print(levelorderTraversal(root))
[[5], [7, 8], [3, 4], [9]]
非递归
def levelorder(root):
if not root:
return []
res=[]
q=[root]
while q:
temp1=[]#存当前层节点
temp2=[]#存下一层的节点
for node in q:
temp1.append(node.val)
if node.left:
temp2.append(node.left)
if node.right:
temp2.append(node.right)
res.append(temp1)
q=temp2#q为下次遍历的当前层
return res
层序遍历非递归输出:
print(levelorderTraversal(root))
[[5], [7, 8], [3, 4], [9]]