Skip to content

Latest commit

 

History

History
62 lines (44 loc) · 1.28 KB

102._binary_tree_level_order_traversal.md

File metadata and controls

62 lines (44 loc) · 1.28 KB

###102. Binary Tree Level Order Traversal

题目:

https://leetcode.com/problems/binary-tree-level-order-traversal/

难度:

Easy

我觉得并不easy

两种做法,利用curLevel和nextLevel来记录,然后按层append.

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        res = []
        
        if root == None: return []
        
        curLevel = [root]
        while curLevel:
            nextLevel = []
            tmpRes = []
            for node in curLevel:
                tmpRes.append(node.val)
                if node.left: nextLevel.append(node.left)
                if node.right: nextLevel.append(node.right)
            res.append(tmpRes)
            curLevel = nextLevel
        
        return res

第二种做法:

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    def preorder(self, root, level, res):
        if root:
            if len(res) < level+1: res.append([])
            res[level].append(root.val)
            self.preorder(root.left, level+1, res)
            self.preorder(root.right, level+1, res)
    def levelOrder(self, root):
        res=[]
        self.preorder(root, 0, res)
        return res