您的位置:首页 > 职场人生

leetcode 面试题32-III 从上到下打印二叉树

2020-06-02 05:22 155 查看

思路:同样是用队列层次遍历二叉树,遍历完完整的一层,再添加到返回结果中,奇数行正序返回,偶数行逆序返回

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root is None:
return []
import queue
q = queue.Queue()
q.put(root)
res = []
while(not q.empty()):
tmp = []
for i in range(q.qsize()):
cur = q.get()
tmp.append(cur.val)
if cur.left:
q.put(cur.left)
if cur.right:
q.put(cur.right)
if len(res) % 2 == 0:#奇数行正序返回,偶数行逆序返回
res.append(tmp)
else:
res.append(tmp[::-1])
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: