剑指offer 牛客网 二叉树的层序遍历

# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 09:33:16 2019 @author: Administrator
层序遍历:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
1
/ \
2 3
/ \ / \
4 5 6 7
返回列表:[1,2,3,4,5,6,7]
""" # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
#层序遍历
def PrintFromTopToBottom(self, root):
# write code here
res,result = [],[]
if root: #非空节点,若空直接返回空
res.append(root) #先将头结点加入其中
i = 0
while True:
if res[i].left: #如果左节点非空将其加入
res.append(res[i].left)
if res[i].right: #同理,右节点非空将其加入
res.append(res[i].right)
i += 1
if i == len(res): #退出条件是当遍历到列表的长度时候退出
break
for i in res: #将节点的值加入到列表返回
if i: #返回非空节点的值
result.append(i.val)
return result if __name__ == '__main__':
solution = Solution()
node_left = TreeNode(4)
node_right = TreeNode(5)
root_left = TreeNode(2)
root_left.left = node_left
root_left.right = node_right node_left = TreeNode(6)
node_right = TreeNode(7)
root_right = TreeNode(3)
root_right.left = node_left
root_right.right = node_right root = TreeNode(1)
root.left = root_left
root.right = root_right res = solution.PrintFromTopToBottom(root)
print(res)
05-08 08:41