zoukankan      html  css  js  c++  java
  • 102. Binary Tree Level Order Traversal

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

    For example:
    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

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

    解题思路:该题的目的是做层序遍历,使用宽度优先搜索(BST),用一个队列queue保存一层的结点,通过遍历queue,取得该层结点的value值,并且在new_q里同步保存下一层结点

    class Solution(object):
        def levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return []
            queue = [root]
            result = []
            while(queue):
                level = []
                new_q = []
                for i in queue:
                    node = i
                    #保存每一层结点的value
                    level.append(node.val)
                    #将下一层的结点保存在new_q队列,当queue队列遍历结束后赋值给queue
                    if(node.left):
                        new_q.append(node.left)
                    if(node.right):
                        new_q.append(node.right)
                queue = new_q    
                result.append(level)  
            return result    
  • 相关阅读:
    CF980E The Number Games
    UVALive 2995 Image Is Everything
    CF1148F Foo Fighters
    CF22E Scheme
    CF1045G AI robots
    学习笔记 并查集维护区间删除
    HEOI 十二省联考退役记
    立方网面试题总结
    Django学习排错备注
    追求卓越之旅(转)
  • 原文地址:https://www.cnblogs.com/bubbleStar/p/6358690.html
Copyright © 2011-2022 走看看