首页 > 其他 > 详细

【LeetCode】面试题32-1. 从上到下打印二叉树

时间:2020-06-09 12:44:33      阅读:44      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

思路:

该题目应该属于Easy类型,利用队列实现层次遍历或者广度优先搜索(BFS)。这里利用list的头插入功能模拟队列。

代码:

Python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        q = []
        q.append(root)
        while q:
            tmp = q.pop()
            if tmp is not None:
                res.append(tmp.val)
                if tmp.left is not None:
                    q.insert(0, tmp.left)
                if tmp.right is not None:
                    q.insert(0, tmp.right)
        return res

相关问题

【LeetCode】面试题32-1. 从上到下打印二叉树

原文:https://www.cnblogs.com/cling-cling/p/13071742.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!