• 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]
    ]
    # 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]]
            """
            if root == None:
                return []
            node_list = []
            node_list.append(root)
            list_value = []
            self.helper(node_list, list_value)
            return list_value 
        def helper(self, node_list, list_value):
            tmp_l_value = []
            tmp_l_node = []
            if node_list != []:
                for i in node_list:
                    tmp_l_value.append(i.val)
                    if i.left != None:
                        tmp_l_node.append(i.left)
                    if i.right != None:
                        tmp_l_node.append(i.right)
                list_value.append(tmp_l_value)
                self.helper(tmp_l_node, list_value)
            
            
        
            

     #非递归,用队列解法

    # 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]]
            """
            if not root :
                return []
            from collections import deque
            q_node = deque([root])
            list_value = []
            while q_node:
                tmp_value = []
                size = len(q_node)
                for i in range(size):
                    node = q_node.popleft()
                    if node.left:
                        q_node.append(node.left)
                    if node.right:
                        q_node.append(node.right)
                    tmp_value.append(node.val)
                list_value.append(tmp_value)
            return list_value
            
            
        
            
  • 相关阅读:
    iOS多线程与网络开发之NSURLCache
    NEFU 117-素数个数的位数(素数定理)
    UISegmentedControl 的使用
    C++使用ADO存取图片
    王立平-- Swift
    浮生猫绘——落入平一的精灵
    BZOJ 1692: [Usaco2007 Dec]队列变换 [后缀数组 贪心]
    POJ2774 Long Long Message [后缀数组]
    BZOJ 2119: 股市的预测 [后缀数组 ST表]
    BZOJ 1717: [Usaco2006 Dec]Milk Patterns 产奶的模式 [后缀数组]
  • 原文地址:https://www.cnblogs.com/boluo007/p/12388526.html
Copyright © 2020-2023  润新知