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]
    ]
    
    Sol 1:
     
    iteration.
     
    Append nodes of current level to a tmp variable. Then if next level has nodes, append them to the next level. Then advance current level to next level. Store the current level to tmp variable before overwritten by the next level. 
     
    # 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]]
            """
            
            # iteration. Time O(n), space O(1)
            # The next level is put in a list. Loop until all levels are added.
            if not root:
                return []
            currentLevel= [root]
            output = []
            while currentLevel:
                tmp = []
                for x in currentLevel:
                    tmp.append(x.val)
                output.append(tmp)
                
                nextLevel = []
                for x in currentLevel:
                    if x.left:
                        nextLevel.append(x.left)
                    if x.right:
                        nextLevel.append(x.right)
                        
                currentLevel = nextLevel
            return output
                

    Sol 2 :

    Recursion. DFS.

    # 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]]
            """
            
            # recursion. Time O(n) Space O(n)
            # better to use iteration in the problem. Iteration: Time O(n) Space(1)
            
            result = []
            # have to input which level to start
            self.level_dfs(root, 0 , result)
            return result
        
        # since recursion is based on the previous result, then result must be in the input of a dfs method
        def level_dfs(self, node, level, result):
            if not node:
                return
            # the length check is neccessay, otherwise the final append will be out of range.
            if level == len(result):
                result.append([])
             
            if node.left:    
                self.level_dfs(node.left, level + 1, result)
            if node.right:
                self.level_dfs(node.right, level + 1, result)
                
            result[level].append(node.val)

    Similar Problem:


    1 Tree Level Order Print 

    https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Trees/Trees%20Interview%20Problems%20-%20SOLUTIONS/Tree%20Level%20Order%20Print%20-%20SOLUTION.ipynb

    314. Binary Tree Vertical Order Traversal

     
  • 相关阅读:
    搭建wamp环境,数据库基础知识
    练习题:选择器和选择好友
    例子:滑动效果
    TCPDump
    内存
    Cache和Buffer的区别(转载)
    经典问题回忆
    history
    DNS
    bc的用法
  • 原文地址:https://www.cnblogs.com/prmlab/p/7154942.html
Copyright © 2011-2022 走看看