具体代码已push到github
树的遍历 github地址
【二叉树的建立】
# 建树
class TreeNode:
def __init__(self, x = -1, left = None, right = None):
self.val = x
self.left = left
self.right = right
class BinaryTree(object):
def __init__(self, root = None):
self.root = root
# 添加节点
def BuildTree(self, root, lis, i = 0):
if i < len(lis):
if lis[i] == '#':
return None
else:
root = TreeNode( x = lis[i])
# print(i)
root.left = self.BuildTree( root.left, lis, 2*i+1 )
root.right = self.BuildTree(root.right, lis, 2*i+2)
return root
return root
【二叉树的遍历】
二叉树的遍历包括深度优先遍历和广度优先遍历。深度优先遍历即deepth First Search,也简称DFS,分为前序遍历,中序遍历和后序遍历。
【前序遍历】
leetcode #144
【原理】根左右
【方法1】 递归实现,按照根左右的顺序递归调用前序遍历函数
# 树节点的定义
#class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = left
# self.right = right
class Solution(object):
def preorderTraversal(self,root):
if root == None:
return []
res = []
self.dfs(root, res)
return res
def dfs(self, root, res):
if root:
#先遍历根节点,然后对根的左子树进行前序遍历,然后对根的右子树进行前序遍历。
res.append(root.val)
self.dfs(root.left, res)
self.dfs(root.right, res)
【非递归方法】
非递归采用栈的方法,将根节点入栈,然后只要栈不空,就pop栈顶元素为根节点,计入结果;继续将此根节点的右子树入栈,然后将左子树入栈。
class Solution(object):
def preorderTraversal(self, root):
if root == None:
return []
stack = [root]
res = []
while stack:
root = stack.pop()
if root:
res.append(root.val)
stack.append(root.right)
stack.append(root.left)
return res
【中序遍历】
leetcode #94
leetcode也带有几种方法的讲解。
【原理】左根右
【递归方式】
class Solution(object):
def inorderTraversal(self,root):
if root == None:
return []
res = []
self.dfs(root, res)
return res
def dfs(self, root, res ):
if root:
self.dfs(root.left, res)
res.append(root.val)
self.dfs(root.right, res)
【非递归】
#非递归
class Solution(object):
def inorderTraversal(self, root):
if root == None:
return []
stack = []
res = []
cur = root
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
【后序遍历】
【原理】 左右根
leetcode #145
【递归】
class Solution(object):
def postorderTraversal(self, root):
if root == None:
return []
res = []
sefl.dfs(root,res)
return res
def dfs(self, root, res):
if root:
self.dfs(root.left, res)
self.dfs(root.right, res)
res.append(root.val)
【非递归】
# 非递归
class Solution(object):
def postorderTraversal(self, root):
if root == None:
return []
stack = [root]
stack2 = []
res = []
while stack:
root = stack.pop()
stack2.append(root)
if root.left:
stack.append(root.left)
if root.right:
stack.append(root.right)
while stack2:
s = stack2.pop().val
res.append(s)
return res
【广度优先遍历】
即一层一层从左向右遍历。
class BFS():
def breathFirstSearch(self,root):
Queen = []
res = []
if root == None:
return None
Queen.append(root)
while Queen:
now_node = Queen.pop(0)
res.append(now_node.val)
# print(now_node.val)
if now_node.left != None:
Queen.append(now_node.left)
if now_node.right != None:
Queen.append(now_node.right)
return res
最后的结果展示可以在github上下载源代码看下。