美文网首页
Binary Tree Level Order Traversa

Binary Tree Level Order Traversa

作者: 你过来啊2018 | 来源:发表于2018-02-24 23:51 被阅读0次

    问题链接

    https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/628/

    解题思路

    1、先序遍历
    2、每次记录层次,作为子数组的index
    3、将每次的root节点append到指定层次的子数组中

    具体代码

    # 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 = []
            self.preorder(res, 0, root)
            return res
            
        def preorder(self, res, level, root):
            if root:
                if len(res) < level + 1:
                    res.append([])
                
                res[level].append(root.val)
                
                self.preorder(res, level + 1, root.left)
                self.preorder(res, level + 1, root.right)
    

    相关文章

      网友评论

          本文标题:Binary Tree Level Order Traversa

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