1.二叉树的结构
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
2.前序遍历(递归)
def preTraverse_recur( pRoot ):
if pRoot==None:
return
res=[]
res.append( pRoot.val )
if pRoot.left!=None:
res.extend( preTraverse_recur( pRoot.left ) )
if pRoot.right!=None:
res.extend( preTraverse_recur( pRoot.right ) )
return res
3.前序遍历(非递归)
def preTraverse_No_recur( pRoot ):
if pRoot == None:
return None
res = []
node_stack = []
p = pRoot
while len(node_stack) > 0 or p != None:
while p != None:
res.append( p.val )
node_stack.append(p)
p = p.left
if len(node_stack) > 0:
p = node_stack[-1]
node_stack.pop(-1)
# res.append( p.val )
p = p.right
return res
4.中序遍历(递归)
def inTraverse_recur( proot ):
res=[]
if proot==None:
return res
if proot.left!=None:
res+=inTraverse_recur( proot.left )
res.append( proot.val )
if proot.right!=None:
res+=inTraverse_recur( proot.right )
return res
5.中序遍历(非递归)
def inTraverse_No_recur( pRoot ):
if pRoot == None:
return None
res = []
node_stack = []
p = pRoot
while len(node_stack) > 0 or p != None:
while p != None:
# res.append( p.val )
node_stack.append(p)
p = p.left
if len(node_stack) > 0:
p = node_stack[-1]
node_stack.pop(-1)
res.append( p.val )
p = p.right
return res
6.后序遍历(递归)
def postTraverse_recur( pRoot ):
res=[]
if pRoot==None:
return res
if pRoot.left!=None:
res+=postTraverse_recur( pRoot.left )
if pRoot.right!=None:
res+=postTraverse_recur( pRoot.right )
res.append( pRoot.val )
return res
7.后序遍历(非递归)
def postTraverse_No_recur( pRoot ):
res=[]
if pRoot==None:
return res
p=pRoot
stack1=[]
stack2=[]
while len( stack1 )>0 or p!=None:
while p!=None:
stack1.append( p )
stack2.append( p )
p=p.right
if len( stack1 )>0:
p=stack1.pop( -1 )
p=p.left
for i in range( len( stack2 ) ):
res.append( stack2.pop( -1 ).val )
return res
8.层序遍历
def seqeueceTraverse( pRoot ):
res=[]
if pRoot==None:
return res
nodes_queue=[]
nodes_queue.append( pRoot )
while len( nodes_queue )>0:
for i in range( len( nodes_queue ) ):
temp=nodes_queue.pop( 0 )
res.append( temp.val )
if temp.left!=None:
nodes_queue.append( temp.left )
if temp.right!=None:
nodes_queue.append( temp.right )
return res