二叉树层次遍历
请设计一个算法从上到下逐层打印二叉树的节点数据,同一层从左到右打印,节点数据类型为整型。
二叉树节点定义如下:
struct Binary TreeNode
(
Int data;
Binary TreeNode * leftChild;
Binary TreeNode * rightChild;
)
请设计一个算法从上到下逐层打印二叉树的节点数据,同一层从左到右打印,节点数据类型为整型。
二叉树节点定义如下:
struct Binary TreeNode
(
Int data;
Binary TreeNode * leftChild;
Binary TreeNode * rightChild;
)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# 生成树的每个节点
class TreeNode:
def __init__(self, data, left, right):
# 节点的数据
self._data = data
# 节点的左子树
self._left = left
# 节点的右子树
self._right = right
# 生成二叉树
class BinaryTree:
# 根节点
def __init__(self):
self._root = None
# 创建根节点
def make_tree(self, treeNode):
self._root = treeNode
# 生成子树
def insert(self, treeNode):
# build a complete binary tree
tList = []
def insert_node(tree_node, p, treeNode):
if tree_node._left is None:
tree_node._left = treeNode
#print("left:",treeNode._data)
tList.append(tree_node._left)
return
elif tree_node._right is None:
tree_node._right = treeNode
#print("right:",treeNode._data)
tList.append(tree_node._right)
return
else:
tList.append(tree_node._left)
tList.append(tree_node._right)
insert_node(tList[p+1], p+1, treeNode)
tList.append(self._root)
insert_node(self._root, 0, treeNode)
# print the result
#print("insert result:")
#for node in tList:
#print(node._data)
# 广度有限
def BFS(tree):
tLst = []
def traverse(node, p):
if node._left is not None:
tLst.append(node._left)
if node._right is not None:
tLst.append(node._right)
if p > (len(tLst)-2):
return
else:
traverse(tLst[p+1], p+1)
tLst.append(tree._root)
traverse(tree._root, 0)
# print the result
for node in tLst:
print(node._data)
# 深度优先
def DFS(tree):
tLst = []
tLst.append(tree._root)
while len(tLst) > 0:
node = tLst.pop()
print(node._data)
if node._right is not None:
tLst.append(node._right)
if node._left is not None:
tLst.append(node._left)
if __name__ == '__main__':
##TList = [1, 3, 2, 5, 4, 6, 8, 7, 9, 12, 11, 14, 13,10]
TList = [1,2,3,4,5,6,7,9,8]
tree = BinaryTree()
for (i, j) in enumerate(TList):
node = TreeNode(j, None, None)
if i == 0:
tree.make_tree(node)
else:
tree.insert(node)
#print("BFS results:")
#BFS(tree)
#print("DFS results:")
DFS(tree)
本文介绍了一种实现二叉树层次遍历的算法,包括广度优先搜索(BFS)和深度优先搜索(DFS),并通过具体代码展示了如何创建二叉树结构,并对创建的二叉树进行层次遍历。
4万+

被折叠的 条评论
为什么被折叠?



