[Binary Tree] Path Sum III

0x00 topic

Given the root node of a binary tree root
and an integer targetSum
, find the number of in the binary tree whose 节点值sum is
equal totargetSum路径

The path does 开始
not need to be from the root node nor at the leaf node 结束
but the path direction must be 向下(only from parent node to child node)

The example is shown in the figure:
Please add image description


0x01 Ideas

This problem is similar to the previous one: Binary Tree Path Sum II

Method 1: It
is equivalent to 每个starting from the node and searching it again

Method 2:
When passing through each layer, save the path of the current node. Find the path
from the current node 向上to the node to
see if there is a 符合conditional path . It has a
kind “一步一回头”of meaning.
Every time you go forward, 回头calculate the path
to see if there is a 符合conditional path.


0x02 solution

language:Swift

tree node:TreeNode

public class TreeNode {
    public var val: Int
    public var left: TreeNode?
    public var right: TreeNode?
    public init() { self.val = 0; self.left = nil; self.right = nil; }
    public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
    public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
        self.val = val
        self.left = left
        self.right = right
    }
}

Solution one:

private var count: Int = 0

func pathSum(_ root: TreeNode?, _ targetSum: Int) -> Int {
    guard let root = root else { return 0 }

    // 从根节点出发
    path(root, targetSum)
    
    // 递归左右节点
    _ = pathSum(root.left, targetSum)
    _ = pathSum(root.right, targetSum)

    return count
}

func path(_ root: TreeNode?, _ sum: Int){
    guard let root = root else { return }

    if root.val == sum {
        count += 1
    }

    // 往下层走,目标值减小
    let val = sum - root.val
    path(root.left, val)
    path(root.right, val)
}

This solution will 重复calculate
the path traversed by the previous layer of nodes many times, and the
next layer of nodes will 重新traverse again

Solution two:

private var count = 0

func pathSum(_ root: TreeNode?, _ targetSum: Int) -> Int {
    var paths: [Int] = []
    dfs(root, targetSum, &paths)
    return count
}

private func dfs(_ root: TreeNode?, _ sum: Int, _ paths: inout [Int]) {
    guard let root = root else { return }
    // 把当前节点值加入路径
    paths.append(root.val)

    // 回头计算路径和
    var currentSum = 0
    var i = paths.count - 1
    while i >= 0 {
        currentSum += paths[i]
        if (currentSum == sum) {
            count += 1 // 符合条件加 1
        }
        i -= 1
    }
    
    // 递归子节点
    dfs(root.left, sum, &paths)
    dfs(root.right, sum, &paths)
    
    // 把当前节点值移除,往回走,走其他路径
    paths.removeLast()
}

applet application

Please add image description


Guess you like

Origin blog.csdn.net/xjh093/article/details/123246525