【剑指Offer】二叉树中和为某一值的路径 解题报告(Python)

2023-02-19,,

剑指Offer】二叉树中和为某一值的路径 解题报告(Python)

标签(空格分隔): 剑指Offer


题目地址:https://www.nowcoder.com/ta/coding-interviews

题目描述:

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

解题方法

其实这个就是一个dfs的问题,遇到的比较多了。第一遍没通过是因为忘了把root.val给放进去了!这个可不能忘啊!!

参考Binary Tree Paths

# -*- coding:utf-8 -*-
# -*- 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):
res = []
if not root: return res
self.target = expectNumber
self.dfs(root, res, [root.val])
return res def dfs(self, root, res, path):
if not root.left and not root.right and sum(path) == self.target:
res.append(path)
if root.left:
self.dfs(root.left, res, path + [root.left.val])
if root.right:
self.dfs(root.right, res, path + [root.right.val])

Date

2018 年 3 月 20 日 – 阳光正好,安心学习

【剑指Offer】二叉树中和为某一值的路径 解题报告(Python)的相关教程结束。

《【剑指Offer】二叉树中和为某一值的路径 解题报告(Python).doc》

下载本文的Word格式文档,以方便收藏与打印。