剑指offer-二叉树中和为某一个值的路径

题目描述:输入一颗二叉树的跟节点和一个整数expectNumber,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

思路:此题需要注意的地方是题目所求路径应该是从根结点开始到叶子结点。

定义数组onepath存放当前遍历的路径,定义patharray数组存放所有符合条件的路径

每遍历一个结点,就将其加入onepath中,并将expectNumber减去这个结点值赋给expectNumber,判定是否符合条件

1.若当前结点为叶子结点且expectNumber等于0,则将该数组放入patharray中,并换其他路径继续搜寻

2.若expectNumber大于0,则向当前结点的左右子树依次优先搜索

3.若expectNumber小于0,则直接换路搜索

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表,内部每个列表表示找到的路径
    def __init__(self):
        self.onepath = [] #存放当前遍历的路径
        self.patharray = [] #存放所有符合条件的路径
    def FindPath(self, root, expectNumber):
        #空树
        if root == None:
            return self.patharray
        self.onepath.append(root.val)
        expectNumber -= root.val
        if expectNumber == 0 and not root.left and not root.right:
            self.patharray.append(self.onepath[:])
        elif expectNumber >0:
            self.FindPath(root.left,expectNumber)
            self.FindPath(root.right,expectNumber)
        self.onepath.pop()
        return self.patharray




猜你喜欢

转载自blog.csdn.net/liuli1926634636/article/details/90056206
今日推荐