Binary Tree Level Order Traversal Leetcode Python

来源:互联网 发布:大连民族学院网络 编辑:程序博客网 时间:2024/05/29 19:28
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,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]

]

这道题的解法在于要定义level 逐层利用preorder traversal 的方法将每个level的值读到解里面。 

We can use preorder traversal to read the node value of the tree based on level.

while root is not none: we read the value. if the length of solution is no greater than the level+1 we add [] to the solution.

Below is the code:

# Definition for a  binary tree node# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    # @param root, a tree node    # @return a list of lists of integers    def levelt(self,root,level,solution):        if root:            if len(solution)<level+1:                solution.append([])            solution[level].append(root.val)            self.levelt(root.left,level+1,solution)            self.levelt(root.right,level+1,solution)    def levelOrder(self, root):        solution=[]        self.levelt(root,0,solution)        return solution        


0 0