路径问题

1. 给一棵BST, 找到从根节点到叶子节点的最小路径和

样例


image.png

Output:10

代码

  • 第一版本
func minimumSum(root *TreeNode) int {

    min := 0
    sum := 0
    minSum(root, &sum, &min)
    return min
}

func minSum(root *TreeNode, sum *int, min *int) {
    if root == nil {
        return
    }
    *sum = *sum + root.Val

    if root.Left == nil && root.Right == nil {
        
        if *min == 0 {
            *min = *sum
        } else if *min > *sum {
            *min = *sum
        }

    }

    minSum(root.Left, sum, min)
    minSum(root.Right, sum, min)
}

image.png
  • 第二版本 o(
func minimumSum(root *TreeNode) int {

    min := 0
    sum := 0
    minSum(root, sum, &min)
    return min
}

func minSum(root *TreeNode, sum int, min *int) {
    if root == nil {
        return
    }
    sum = sum + root.Val

    if root.Left == nil && root.Right == nil {

        if *min == 0 {
            *min = sum
        } else if *min > sum {
            *min = sum
        }

    }

    minSum(root.Left, sum, min)
    minSum(root.Right, sum, min)
}

image.png

bst特性没有利用上 因为深度不确定 在小数值累计起来大于

  • 第三版本
//总耗时 920 ms
func minimumSum(root *TreeNode) int {
    if root == nil {
        return 0
    }

    left := minimumSum(root.Left)
    right := minimumSum(root.Right)
    if left == 0 {
        return right + root.Val
    } else if right == 0 {
        return left + root.Val
    }
    return min(left, right) + root.Val

}

64. Minimum Path Sum

image.png

https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-64-minimum-path-sum/
image.png

能不能在优化?
Time complexity: O(mn)

Space complexity: O(1)

你可能感兴趣的:(路径问题)