面试34题:

题目:二叉树中和为某一值的路径

题:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

解题代码:

# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
if not root:
return []
result=[] def FindPathCore(root,path,currentNum):
currentNum += root.val
path.append(root)
# 判断是否达到叶子节点
flag = (root.left==None and root.right==None) #如果到达叶子节点且当前值等于期望值
if currentNum==expectNumber and flag:
onepath=[]
for node in path:
onepath.append(node.val)
result.append(onepath) if currentNum<expectNumber:
if root.left:
FindPathCore(root.left,path,currentNum)
if root.right:
FindPathCore(root.right,path,currentNum)
path.pop() FindPathCore(root,[],0)
return result

最新文章

  1. java接口的嵌套
  2. ubuntu 下安装redis 以及php扩展
  3. matlab之meshgrid()函数
  4. Django TemplateSyntaxError Could not parse the remainder: &#39;()&#39;
  5. Oracle 恢复被删除的数据,解决误操作删除数据
  6. 浅谈setTimeout函数和setInterval函数
  7. myeclipse下安装svn
  8. bug的约束
  9. socket对于大数据的发送和接收
  10. RFID FDX HDX Technology
  11. 如何清除Linux 登陆信息及日志
  12. iot 表 主键索引叶子块包含了表所有数据
  13. 安装 CentOS 7 后必做的七件事
  14. websphere:rs.getDate()无法使用的解决方法
  15. dotnet检测类型是否为泛型
  16. 没有显示器如何SSH连接上树莓派
  17. python---读取/写入excel用例数据
  18. UltraVNC 简体中文版 1.2.2.1
  19. day32-常见内置模块一(random、time、datetime、os、sys)
  20. Java 配置环境变量教程

热门文章

  1. Django的自定义标签
  2. MD5摘要(Java实现)
  3. neocomplcache 自动补全
  4. 通过Get方式传递数据
  5. Photoshop脚本之创建文件夹
  6. 报错:org.apache.jasper.JasperException: /jsp/head.jsp (line: 1, column: 2) Page directive: illegal to
  7. HTTPS请求 SSL证书验证
  8. 【剑指Offer面试题】 九度OJ1518:反转链表
  9. Python如何利用多核处理器
  10. 47、ListView setSelection() 和 setSelectionFromTop()