百度面试题之二叉树层次遍历(从上到下,从下到上)

时间:2023-01-26 17:27:34

1.二叉树的层次遍历 递归解法

class Node(object):
def __init__(self, v, left=None, right=None):
self.value = v
self.left = left
self.right = right

# 层次遍历入口函数
def level_tranverse_iterate(node):
if not node:
return 0
depth = Depth(node)
print "depth:", depth
for i in range(1, depth+1):
print_node_at_level(node, i)
print

# 计算树高
def Depth(node):
if not node:
return 0
return max(Depth(node.left)+1,Depth(node.right)+1)

# 当level=1时才输出结点
def print_node_at_level(node, level):
if not node or level < 1:
return 0
if level == 1:
print node.value,
return 0
print_node_at_level(node.left, level-1)
print_node_at_level(node.right, level-1)


node = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4)))
level_tranverse_iterate(node)
# output:
depth: 4
1
3 2
7 6 5 4
0

2.非递归解法

def level_tranverse_noniterate(node):
stack = [node]
while stack:
node = stack.pop(0)
print node.value
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)


node = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4)))

level_tranverse_noniterate(node)
output:
1 3 2 7 6 5 4 0

3.从底向上的层次遍历 非递归解法

就是将树
1
3 2
7 6 5 4
0
打印为:
0 7 6 5 4 3 2 1

主要是要考虑每层的元素要分隔开,不然会乱。

# python 2.7
def from_bottom_to_top(node):
if not node:
return 0

vect = [node]
cur = 0
last = 1

while cur < len(vect):
vect.append(None) # 以None作为层之间的分隔
last = len(vect)
print "每层个数"+str(last-cur)
# 每层的结点都判断是否有左右子结点
# 用cur来计数,cur==last-1即当前层的结点全部判断完了
#然后cur += 1,如果cur==len(vect),说明下一层没有新结点加入,层次遍历结束
while cur < last - 1:
if vect[cur].right:
vect.append(vect[cur].right)
if vect[cur].left:
vect.append(vect[cur].left)
cur += 1
cur+= 1

# 按层输出
for i in range(len(vect)):
if vect[i]:
print vect[i].value,
else:
print