温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

leetcode--二叉树的层次遍历

发布时间:2020-07-29 16:23:27 来源:网络 阅读:279 作者:ading2016 栏目:编程语言

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
# 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 not root:
            return []
        res = []
        cur_node = [root]
        next_node = []
        res.append([i.val for i in cur_node])
        while cur_node or next_node:
            for node in cur_node:
                if node.left:
                    next_node.append(node.left)
                if node.right:
                    next_node.append(node.right)
            if next_node:
                res.append([
                    i.val for i in next_node
                ])
            cur_node = next_node
            next_node = []
        return res

执行用时 : 80 ms, 在Binary Tree Level Order Traversal的Python3提交中击败了26.32% 的用户

内存消耗 : 13.2 MB, 在Binary Tree Level Order Traversal的Python3提交中击败了98.08% 的用户


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI