找到二叉树所有和为指定值的路径

使用前序遍历可以获得所有到达叶子结点的路径

注:代码中使用的Tree2类可以从链接中获取

# form a binary tree
import Tree2
tree = Tree2.BinTree()
for i in range(1,9):
    tree.add(i)
tree.add(10)
tree.add(9)
# tree.out_value_levelorder()

# find a path, sums of nums in these paths equal the target value
from collections import deque # Double ended queue, STL
def FindAllPath(rootnode,expectednum):
    if not rootnode:
        return
    currentsum=0
    path = deque()
    searchpath(rootnode,expectednum,currentsum,path)
def searchpath(rootnode,expectednum,currentsum,path):
    currentsum+=rootnode.data
    path.append(rootnode.data)
    # print(path)
    notleaf = rootnode.left and rootnode.right
    if (not notleaf and currentsum==expectednum):
        print('find a path and now printing...')
        for value in path:
            print(value)
    if (rootnode.left):
        searchpath(rootnode.left,expectednum,currentsum,path)
    if (rootnode.right):
        searchpath(rootnode.right,expectednum,currentsum,path)
    # if run there, mean counter leaf node
    # print('is leaf')
    # if arrive leaf node and path do not satisfy, trackback currentsum and path
    currentsum-=rootnode.data
    path.pop()

# test
FindAllPath(tree.root,17)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JZ34题目要求我们 在给定的二叉树中找出所有和为指定路径。这道题是JZ24二叉树中和为某一路径的加强版,因为它需要我们找出所有符合要求的路径,而不是从根节点到叶节点的一条路径。 我们可以采用深度优先遍历(DFS)的方法来解决这个问题。具体做法如下: 1. 首先我们需要定义一个函数,用于遍历二叉树: ```python def dfs(node, target, path, result): # node表示当前遍历的节点 # target表示剩余的目标值 # path表示当前已选择的路径 # result表示符合要求的路径列表 # 如果遍历到了空节点,直接返回 if not node: return # 把当前节点添加到路径中 path.append(node.val) # 计算当前剩余的目标值 target -= node.val # 如果目标值为0,说明找到了一条符合要求的路径,将其加入结果列表中 if target == 0 and not node.left and not node.right: result.append(path[:]) # 继续递归遍历左右子树 dfs(node.left, target, path, result) dfs(node.right, target, path, result) # 回溯,将刚刚添加的节点从路径中删除 path.pop() ``` 2. 然后我们需要遍历整个二叉树,对于每个遍历到的节点,都调用一次`dfs`函数,将其作为先前路径中的一部分,并且更新`target`的: ```python def find_path(root, target): result = [] dfs(root, target, [], result) return result ``` 这样,我们就可以得到所有符合要求的路径了。 总之,这道题需要我们具备二叉树基础知识和DFS基础知识,我们需要仔细阅读题目并思考,再将自己的思路转化为代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值