LeetCode 102 && 429 广度优先遍历

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zone_/article/details/83826533

本文首发于公众号「zone7」,关注获取最新推文!

image

概述

  • 前言
  • 429 N 叉树的层次遍历 90.36%
  • 102 二叉树的层次遍历 99.76%
  • 后记

前言

不管经济多不好,提高自身硬实力才是关键。最近我也开始刷题了,所以后面的文章会时不时出现 LeetCode 的题。希望我们一起提高,一起进步。

429 N 叉树的层次遍历 90.36%

给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。

例如,给定一个 3叉树 :

返回其层序遍历:

[
     [1],
     [3,2,4],
     [5,6]
]

说明:

  1. 树的深度不会超过 1000
  2. 树的节点总数不会超过 5000

思路

如果你有读我前面的文章就知道,其实这个就是二叉树层次遍历的一个变形。

for child in current.children:    
                    que.append(child);

用这句代码替换了左右子树加入队列。

解答

# 运行效率:90.36%
"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):

    def levelOrder(self, root):
        """
        :type root: Node
        :rtype: List[List[int]]
        """
        if not root:
            return [];
        que = [];    
        res = [];    
        que.append(root);    
        while len(que):     
            l = len(que);
            sub = [];        
            for i in range(l):
                current = que.pop(0);    
                sub.append(current.val);
                for child in current.children:    
                    que.append(child);
            res.append(sub);    
        return res;

102 二叉树的层次遍历 99.76%

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

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

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]

思路

嗯,这就是上篇文章《python 实现二叉树的深度&&广度优先的遍历》中的层次遍历代码。不用解释太多了。

解答

# 运行效率:99.76%
# 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):
        if not root:
            return []
        ret = []
        ret.append(root)
        ret2 = []
        while len(ret) != 0:
            temp = []
            length = len(ret)
            for index in range(length):
                tempValue = ret.pop(0)
                temp.append(tempValue.val)
                if tempValue.left is not None:
                    ret.append(tempValue.left)
                if tempValue.right is not None:
                    ret.append(tempValue.right)
            ret2.append(temp)
        return ret2

后记

今天的题就到这里了,如果有什么好刷题的建议可以留言或者后台私信给我,我会分享给大家。

猜你喜欢

转载自blog.csdn.net/zone_/article/details/83826533