1、递归实现二叉树的前中后序遍历
>二叉树的前序遍历
def preorderTraversal ( node: TreeNode, result: list ) :
if node is None :
return
result. append( node. val)
if node. left is not None :
preorderTraversal( node. left, result)
if node. right is not None :
preorderTraversal( node. right, result)
>二叉树的中序遍历
def inorderTraversal ( node: TreeNode, result: list ) :
if node is None :
return
if node. left is not None :
inorderTraversal( node. left, result)
result. append( node. val)
if node. right is not None :
inorderTraversal( node. right, result)
>二叉树的后序遍历
def postorderTraversal ( node: TreeNode, result: list ) - > list :
if node is None :
return
if node. left is not None :
postorderTraversal( node. left, result)
if node. right is not None :
postorderTraversal( node. right, result)
result. append( node. val)
2、非递归实现二叉树的前中后序遍历
>二叉树前序遍历的实现
def preorderTraversal ( node: TreeNode) :
if root is None :
return [ ]
stack = [ root]
result = [ ]
while stack != [ ] :
temp = stack. pop( )
result. append( temp. val)
if temp. right is not None :
stack. append( temp. right)
if temp. left is not None :
stack. append( temp. left)
return result
>二叉树的中序遍历实现
def inorderTraversal ( node: TreeNode) - > list :
temp = node
stack = [ ]
result = [ ]
while temp is not None or stack!= [ ] :
if temp is not None :
stack. append( temp)
temp = temp. left
else :
temp = stack. pop( )
result. append( temp. val)
temp = temp. right
return result
>二叉树的后序遍历
def postorderTraversal ( root: TreeNode) - > list :
if root is None :
return [ ]
stack = [ ]
result = [ ]
prev = None
while root is not None or stack != [ ] :
while ( root is not None ) :
stack. append( root)
root = root. left
root = stack. pop( )
if ( root. right is None ) or ( root. right == prev) :
result. append( root. val)
prev = root
root = None
else :
stack. append( root)
root = root. right
return result
层次遍历(以leetcode102题层次遍历为例)
def levelOrder ( root: TreeNode) - > list :
if root is None :
return [ ]
from queue import Queue
save_queue = Queue( )
result = [ ]
save_queue. put_nowait( root)
while not save_queue. empty( ) :
temp_nodes = [ ]
temp_val = [ ]
while not save_queue. empty( ) :
temp_node = save_queue. get_nowait( )
temp_nodes. append( temp_node)
temp_val. append( temp_node. val)
result. append( temp_val)
for temp_node in temp_nodes:
if temp_node. left is not None :
save_queue. put_nowait( temp_node. left)
if temp_node. right is not None :
save_queue. put_nowait( temp_node. right)
return result