美文网首页Leetcode
102. Binary Tree Level Order Tra

102. Binary Tree Level Order Tra

作者: oo上海 | 来源:发表于2016-08-05 04:01 被阅读9次

    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
    

    用递归来记录每一层,需要更加学习,不算easy

    相关文章

      网友评论

        本文标题:102. Binary Tree Level Order Tra

        本文链接:https://www.haomeiwen.com/subject/wkdhsttx.html