zoukankan      html  css  js  c++  java
  • 【leetcode-102】二叉树的层序遍历

    102-二叉树的层序遍历

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

    题目分析

    此题类似于《剑指offer》的第32题

    层序遍历二叉树是指对二叉树每一层从左到右进行访问。

    • 非叶子节点

      对于每一层的非叶子节点,都有两个子节点。在层序遍历时,上一层非叶子节点的遍历顺序,和下一层的叶子节点的遍历顺序是相同的。

      因此对于下一层的节点来说,可以在遍历上一层节点时,使用容器存储起来。

    • 容器的选择

      可以观察到节点的访问顺序与放入容器的顺序是相同的,因此可以使用一个栈结构来存储下层的节点。

    • 每层遍历开始和结束的判断

      因为要判断每一层是否遍历完,需要一个变量记录每层的节点数目

    • 将每层按照标准结果输出

      这道题需要把每层作为一个list添加到result中

    实现代码

     
    # 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 = []
             res_val = []
             res.append(root)
             nextLevel = 0
             toBeAppended = 1
             temp = []
             while len(res)>0:
                 node = res.pop(0)
                 temp.append(node.val)
     ​
                 # 这里一定注意要先放左节点再放右节点
                 if node.left:
                     res.append(node.left)
                     nextLevel +=1
                 if node.right:
                     res.append(node.right)
                     nextLevel +=1
                 
                 #del res[0]
                 toBeAppended -= 1
                 if toBeAppended == 0:
                     res_val.append(temp)
                     toBeAppended = nextLevel
                     nextLevel = 0
                     temp = []
             return res_val
     
    # 实现方法2
     # 使用容器代替计数
     class Solution:
         def levelOrder(self, root: TreeNode) -> List[List[int]]:
             if not root:
                 return []
             res, curnodes = [], [root]
             while curnodes:
                 curvals, nextnodes = [], []
                 for node in curnodes:
                     curvals.append(node.val)
                     if node.left:
                         nextnodes.append(node.left)
                     if node.right:
                         nextnodes.append(node.right)
                     res.append(curvals)
                     curnodes = nextnodes
             return res            
  • 相关阅读:
    双重检查锁定(Double-Checked Locking)与延迟初始化(Lazy Initialization)
    Spring Cloud Zookeeper搭建实例
    Spring Boot读取properties
    快速搭建单机版Spring Cloud EurekaServer
    MyBatis PageHelper分页插件
    MyBatis Generator 逆向工程插件
    快速搭建单机版Spring Cloud EurekaServer
    什么是JWT令牌认证?
    Spring Boot高频面试题:Spring Boot执行原理
    SOLID原则都不知道,还敢说自己是搞开发的!
  • 原文地址:https://www.cnblogs.com/szxyx/p/13330082.html
Copyright © 2011-2022 走看看