# 001.树——二叉树

## 1.代码

# 树结点
class TreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right

# 树类
class Tree:
def __init__(self):
self.root = None
self.queue = list()

node = TreeNode(data)
if not self.root:  # 空树的情况下
self.root = node
self.queue.append(self.root)
else:
cur = self.queue[0] # 将第一个结点取出
if cur.left is None:    # 为该结点添加左子树
cur.left = node
self.queue.append(cur.left)
elif cur.right is None: # 为该结点添加右子树
cur.right = node
self.queue.append(cur.right)
self.queue.pop(0)   # 添加完毕，从队列中取出

def BFS(self, root):    # 层次遍历，使用队列
if not root:
return None

queue = list()
bfs_res = list()    # 结果列表
queue.append(root)
while queue:
node = queue.pop(0)
bfs_res.append(node.data)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)

return bfs_res

def preTraverse(self, root):    # 深度优先 - 前序
pre_res = list()

def pre(root):
if not root:
return

pre_res.append(root.data)
pre(root.left)
pre(root.right)

pre(root)
return pre_res

def midTraverse(self, root):    # 深度优先 - 中序
mid_res = list()

def mid(root):
if not root:
return

mid(root.left)
mid_res.append(root.data)
mid(root.right)

mid(root)
return mid_res

def postTraverse(self, root):   # 深度优先 - 后序
post_res = list()

def post(root):
if not root:
return

post(root.left)
post(root.right)
post_res.append(root.data)

post(root)
return post_res

def leaveNode(self, root):  # 应用-叶子结点
lev_res = list()

def leave(root):
if not root:
return

if not root.left and not root.right:
lev_res.append(root.data)
leave(root.left)
leave(root.right)

leave(root)
return lev_res

def heightOfTree(self, root):   # 应用-高度
def height(root):
if not root:
return 0

left_depth = height(root.left)
right_depth = height(root.right)

return max(left_depth, right_depth) + 1

return height(root)

def main():
while True:
try:
nums = list(input().strip().split())
tree = Tree()   # 建立二叉树
for num in nums:    # 添加结点
bfs_res = tree.BFS(tree.root)   # 广度优先遍历
print("广度优先：{}".format(bfs_res))
pre_res = tree.preTraverse(tree.root)   # 深度优先遍历 - 前序遍历
print("前序遍历：{}".format(pre_res))
mid_res = tree.midTraverse(tree.root)   # 深度优先遍历 - 中序遍历
print("中序遍历：{}".format(mid_res))
post_res = tree.postTraverse(tree.root)  # 深度优先遍历 - 后序遍历
print("后序遍历：{}".format(post_res))
lev_res = tree.leaveNode(tree.root)  # 叶子结点
print("叶子结点：{}".format(lev_res))
height = tree.heightOfTree(tree.root)  # 叶子结点
print("高度：{}".format(height))
except EOFError:
break

if __name__  == "__main__":
main()


03-23 459
04-22
01-03 224
06-03
01-06 2250
06-19
09-22 708
04-07 9723
02-18
11-19 52
11-06 679
11-16 1173
11-16 803