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]
    ]

    道理我都懂,怎么用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[List[int]]
            """
            res = []
            if not root:
                return res
            temp = [root]
            while temp:
                cur = []
                next_temp = []
                for node in temp:
                    cur.append(node.val)
                    if node.left:
                        next_temp.append(node.left)
                    if node.right:
                        next_temp.append(node.right)
                res.append(cur)
                temp = next_temp
            return res

     思路就是用temp表示当前层节点,next_temp表示下一层节点

    通过node不断访问

    用cur保存每一层的结果然后添加到res结果里面

  • 相关阅读:
    2019.8.6原型链与继承
    2019.8.2闭包,作用域
    2019.8.1正则二
    2019.7.31正则
    2019.7.29二维数组
    2019.7.28关于数组和循环的八道题
    2019.7.27数组api
    DOM
    JavaScript数组5种去重方法
    JavaScript面向对象
  • 原文地址:https://www.cnblogs.com/dmndxld/p/10890760.html
Copyright © 2011-2022 走看看