Path Sum III(leetcode)

Path Sum III--找出二叉树中符合要求的路径数


  这是一个leetcode上的难度为easy的题,但是整个题目的标记难度为easy,虽然题目难度标记为简单,但是整个题目还是蛮有有趣的,因此这里我们来分享这道题的思路。


题目描述

  整个程序的描述还是比较简单的,这里我把原题目贴出来。

You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

  整个题目的大致如下:有一个二叉树,树的每个节点包含一个整数,找到一个路径的总数,这个路径满足的条件是:该路径上的节点所代表的值的总和等于我们给定的一个数。这个路径并不要求从根节点开始,同时也不要求到叶节点结束,但是它必须是向下的(必须父节点到子节点)。同时告诉了你的树的范围(少于1000个节点,同时树中节点的范围也给出了)。

解题思路

  对于二叉树的问题,我一贯的思想就是:没有遍历解决不了的事情,选择适合问题的遍历方式,同时选择递归还是非递归,只要选对了方法,问题就已经解决了一半。对于这个问题,我的第一直觉就是采用后序递归的非递归方式。原因如下:

  1. 虽然递归的方式比较简单,但是不便于我们理解程序具体内部的执行过程,所以这个题目,我决定还是非递归的方式。
  2. 再4种遍历方式中(先序,中序,后序,层次),我们可以看到后序遍历中的一个特点:在后序遍历的非递归形式中,每当遍历一个节点的时候,栈中所保存的节点正好是根节点到该节点的路径,利用这个特性可以让我们计算整个路径下的值,从而计算整个路径的总数。

  虽然这个问题看上去已经解决了,但是我在编写程序的时候,还是遇到了很多情况,同时也遇到了很多没有考虑到的情况。这里就不一一赘述了。

程序代码

  这里我采用了Python来编写这个题的代码,可以看到:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
  # 下面这个函数帮助我们来每次遍历节点的时候统计路径的数量
  def traversal_stack(test: 'List[TreeNode]',node_value:int, target:int):
            temp = target - node_value 
            count_result = 0
            if temp == 0:
                count_result = 1
                i = len(test) - 1
                temp_sum = 0
                while i >= 0:
                    temp_sum += test[i].val
                    if temp_sum == 0:
                        count_result += 1
                    i -= 1
                return count_result
            if len(test) != 0:
                i = len(test) - 1
                while i >= 0:
                    temp -= test[i].val
                    if temp == 0:
                        count_result += 1
                    i -= 1
                return count_result
            else:
                return 0
    def pathSum(self, root: TreeNode, sum: int) -> int:
        current = root  # current记录当前指向的节点
        last = None  # 记录上一次遍历的节点
        stack = []  # 后序遍历时候用到的栈
        count = 0  # count 记录总的路径数
        if root is None:
            return 0
        else:
            while current is not None:  # 后序遍历 不断将左孩子节点进栈
                    stack.append(current)
                    current = current.left
            while len(stack) != 0:
                current = stack.pop()  # 取当前节点
                if current.right is None or current.right == last:
                    # 进行计数
                    count += traversal_stack(stack, current.val, sum)
                    last = current
                else:
                    stack.append(current)
                    current = current.right
                    while current is not None:
                        stack.append(current)
                        current = current.left
            return count
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值