剑指offer:二叉树中和为某一值的路径(Python)

站在巨人的肩膀上,风景这边独好;
亲自爬上巨人的肩膀,才知风景为什么这么美。

题目描述

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

解题思路

– 注意到路径必须为跟节点 –> 没有左右子树的叶子节点;定义两个数组pathArray、onePath,pathArray用于存储所有符合条件的路径,onePath用于存储当前遍历的路径;
– 类似于深度优先搜索,每遍历到一个节点,就将其加入到onePath中,并判定是否符合条件:
1. 为叶节点且和等于要求的整数,则将该数组存储至pathArray中,并换其他路径继续搜寻;
2. 和小于要求的整数,则向当前节点的左右子树依次深度优先搜索;
3. 和大于要求的整数,则直接换路搜索。

代码草稿

import copy
class Solution:
    def FindPath(self, root, expectNumber):
        onePath = []
        pathArray = []
        self.Find(root, expectNumber, onePath, pathArray)
        return pathArray

    def Find(self, root, expectNumber, onePath, pathArray):
        if root == None:
            return pathArray

        onePath.append(root.val)
        if self.getSum(onePath) == expectNumber and not root.left and not root.right:
            pathArray.append(copy.deepcopy(onePath))
        elif self.getSum(onePath) < expectNumber:
            if root.left != None:
                self.Find(root.left, expectNumber, onePath, pathArray)
                onePath.pop(-1)
            if root.right != None:
                self.Find(root.right, expectNumber, onePath, pathArray)
                onePath.pop(-1)
        elif self.getSum(onePath) > expectNumber:
            onePath.pop(-1)

    def getSum(self, array):
        sum = 0
        for i in array:
            sum += i
        return sum

为了不让其他因素干扰到思路,写代码时完全不考虑美观和简洁;Python是优雅的,好的程序一定是赏心悦目的。如果代码逻辑很丑陋,那一定是自己的问题… 所以现在到了改正自己问题的时候了~:

待优化:
1. 写三个函数,只为实现一个功能;第一个函数只是为了声明变量而存在,第二个函数传入的变量则过多,第三个函数则无存在的必要;
2. 代码不够精炼,数组元素弹出操作、判断节点是否为空的操作均出现多次。

优化后的代码

class Solution:
    def __init__(self):
        self.onePath = []
        self.PathArray = []
    def FindPath(self, root, expectNumber):
        if root is 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

能优化成这个样子,还是要感谢这篇博客代码写得够简洁啊[捂脸]

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值