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]
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
- Binary Tree Level Order Traversal Leetcode Python
- 【Leetcode】【python】Binary Tree Level Order Traversal
- LeetCode[Tree]: Binary Tree Level Order Traversal
- *(leetcode) Binary Tree Level Order Traversal (tree)
- [leetcode][tree] Binary Tree Level Order Traversal
- 【LeetCode with Python】 Binary Tree Level Order Traversal
- 【LeetCode with Python】 Binary Tree Level Order Traversal II
- Python学习——leetcode(Binary Tree Level Order Traversal)
- 103. Binary Tree Zigzag Level Order Traversal Leetcode Python
- 【leetCode】Binary Tree Zigzag Level Order Traversal python实现
- 【leetCode】Binary Tree Level Order Traversal python实现
- [leetcode: Python]102. Binary Tree Level Order Traversal
- [leetcode: Python]107.Binary Tree Level Order Traversal 2
- 【Leetcode】【python】Binary Tree Zigzag Level Order Traversal
- 【Leetcode】【python】Binary Tree Level Order Traversal II
- LeetCode 102. Binary Tree Level Order Traversal(Python)
- LeetCode: Binary Tree Level Order Traversal
- LeetCode: Binary Tree Zigzag Level Order Traversal
- java 图片验证码
- 遍历set
- 时间复杂度
- Python 使用nltk和BeautifulSoup进行数据清理 (去除html tag和转换html entities)
- 持续集成工具
- Binary Tree Level Order Traversal Leetcode Python
- 堆结构(三) - 斜堆的原理与实现
- 自主的文件缓存组件FileCache和被封装的System.Net.Cache
- 图结构(一)- 图的理论基础
- Light is falling on a tree from left side you have to find all the nodes on which this light will fa
- 103. Binary Tree Zigzag Level Order Traversal Leetcode Python
- GDB调试之重定向
- EventBus小记
- Leetcode NO.73 Set Matrix Zeroes