数据结构–树的python实现
相对于链表、栈和队列,树的结构是最复杂的。本文在实现的时候会把树的各操作分开写,各个击破。
1.构造树
class TreeNode: #首先定义树的节点
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self, item):
node = TreeNode(item)
if self.root == None: #tree为空的情况,直接赋值给root
self.root = node
return
queue = [self.root] #tree不为空的情况,根据root逐步去找插入位置
while queue: #过程类似于广度优先遍历
cur_node = queue.pop(0)
if cur_node.left == None: #左孩子为空则直接赋值,否则存储左节点,下一层再弹出
cur_node.left == node
return
else:
queue.append(cur_node.left)
if cur_node.right == None:
cur_node.right == node
return
else:
queue.append(cur_node.right)
2.广度优先遍历
- 第一种写法
def breadth_travel():
if root == None: return None
res = []
stack = [root]
while stack:
node = stack.pop(0)
res.append(node.val)
if node.left != None:
stack.append(node.left)
if node.right != None:
stack.append(node.right)
return res #res存储了广度优先遍历结果
- 第二种写法
def breadth_travel():
if root == None: return None
res = []
stack = [root]
while stack:
temp = [] #存储每一层的节点
for node in stack:
res.append(node.val)
if node.left != None:
temp.append(node.left)
if node.right != None:
temp.append(node.right)
stack = temp
return res
3.深度优先遍历
- 递归实现
def binaryTreePaths(): #深度搜索,返回各条路径
if root == None: return []
res = []
dfs(root, res, [root.val])
return res
def dfs(root, res, path):
if root.left == None and root.right == None:
res.append(path)
if root.left != None:
dfs(root.left, res, path+[root.left.val])
if root.right != None:
dfs(root.right, res, path+[root.right.val])
- 非递归实现
def binaryTreePaths(): #深度搜索,返回各条路径
if root == None: return []
res = []
stack= [] #需要辅助栈
stack.append((root, [root.val]))
while stack:
node, path = stack.pop()
if node.left == None and node.right == None:
res.append(path)
if node.left != None:
stack.append((node.left, path+[node.left.val]))
if node.right != None:
stack.append((node.right, path+[node.right.val]))
return res
方法2与方法1得到的结果是相反的(逆序的),因为方法2非递归实现用了pop,先入栈的后弹出。