lintcode 二叉树的层次遍历
来源:互联网 发布:淘宝动态计算器 编辑:程序博客网 时间:2024/06/07 01:27
问题描述
http://www.lintcode.com/zh-cn/problem/binary-tree-level-order-traversal/#
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {3,9,20,#,#,15,7} :
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
先从最简单的问题开始
遍历二叉树的第k层,相当于遍历二叉树根节点的左右子树的第k-1层。这样一直遍历下去,直到k=0时,输出节点即可。
def printnode(TreeNode root, int k,list l): if(not root or k<0): return 0 if(k==0): l.append([root.val]) return 0 else: l.append([printnode(root.left,k-1), printnode(root.left,k-1)] return 0
层次遍历
写一个for循环即可
for i in range(max_depth): printnode(root,i,l)
完整代码
"""Definition of TreeNode:class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None"""class Solution: """ @param: root: A Tree @return: Level order a list of lists of integer """ """Definition of TreeNode:class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None"""class Solution: """ @param: root: A Tree @return: Level order a list of lists of integer """ def printnode(TreeNode root, int k,list l): if(not root or k<0): return 0 if(k==0): l.append([root.val]) return 0 else: l.append([printnode(root.left,k-1), printnode(root.left,k-1)] return 0 def levelOrder(self, root): # write your code here max_depth=3 queue=[] for i in range(max_depth): self.printnode(self.root,i,queue) return queue
阅读全文
0 0
- LintCode-二叉树的层次遍历 II
- LintCode 二叉树的层次遍历
- LintCode 二叉树的层次遍历 II
- lintcode-二叉树的层次遍历-69
- LintCode:二叉树的层次遍历
- LintCode:二叉树的层次遍历 II
- LintCode:二叉树的锯齿形层次遍历
- LintCode 二叉树的锯齿形层次遍历
- Lintcode(M) 二叉树的层次遍历
- 二叉树的锯齿形层次遍历,lintcode
- 二叉树的层次遍历 II,lintcode
- 二叉树的层次遍历,lintcode
- LintCode 69-二叉树的层次遍历
- LintCode | 69. 二叉树的层次遍历
- LintCode-二叉树的层次遍历
- lintcode 二叉树的层次遍历
- LintCode 二叉树的层次遍历
- 二叉树的层次遍历-LintCode
- Sersync github镜像 二进制包
- R语言画图
- Linux 常用命令之二
- 23个设计模式--(一)、单例模式
- 机器学习之分类学习(模型训练)
- lintcode 二叉树的层次遍历
- Flask零基础到项目实战(六)模型分文件
- 给div加focus和查看当前focus的元素
- hdu2481
- 处理机管理功能
- 一些富有创意的Demo
- shiro-spring 结合的配置问题
- struts2学习心得
- 粗体判断js中的数据类型有一下几种方法