树是数据结构中非常重要的一种,主要的用途是用来提高查找效率,对于要重复查找的情况效果更佳,如二叉排序树、FP-树。另外可以用来提高编码效率,如哈弗曼树。
递归实现先序遍历、中序遍历、后序遍历
先序遍历
先序遍历
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
#递归写法
result=[]
def pre(root,result):
if root==None:
return None
result.append(root.val)
pre(root.left,result)
pre(root.right,result)
pre(root,result)
return result
中序遍历
def middle_digui(self, root):
"""利用递归实现树的中序遍历"""
if root == None:
return
self.middle_digui(root.lchild)
print (root.val)
self.middle_digui(root.rchild)
后序遍历
def later_digui(self, root):
"""利用递归实现树的后序遍历"""
if root == None:
return
self.later_digui(root.lchild)
self.later_digui(root.rchild)
print (root.elem)
堆栈实现先序遍历、中序遍历、后序遍历
先序遍历
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root==None:
return None
result=[]
stack=[]
node=root
while node or stack:
while node:
result.append(node.val)
stack.append(node)
node=node.left
node=stack.pop()
node=node.right
return result
中序遍历
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root==None:
return None
result=[]
stack=[]
node=root
while node or stack:
while node:
stack.append(node)
node=node.left
node=stack.pop()
result.append(node.val)
node=node.right
return result
后序遍历
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result=[]
stack1=[]
stack2=[]
if root==None:
return result
stack1.append(root)
while stack1:
cur=stack1.pop()
if cur.left:
stack1.append(cur.left)
if cur.right:
stack1.append(cur.right)
stack2.append(cur)
while stack2:
tmp=stack2.pop()
result.append(tmp.val)
return result
层序遍历
def level_queue(self, root):
"""利用队列实现树的层次遍历"""
if root == None:
return
myQueue = []
node = root
myQueue.append(node)
while myQueue:
node = myQueue.pop(0)
print node.elem,
if node.lchild != None:
myQueue.append(node.lchild)
if node.rchild != None:
myQueue.append(node.rchild)