DWQA QuestionsCategory: ProgramAn algorithm problem that initializes a binary tree with Python and solves its shortest path value
Kami asked 2 weeks ago

A binary tree, each node has its own value, in the binary tree to find a path (the path between the root node and a leaf node is the path), the value of all nodes on the minimum output value is what! The shortest path here is not by hops, but by the sum of node values. Don’t make a mistake!
If the input is 0 at the beginning of a line, the end of the input is indicated, and the empty node is null.

2       3


            2                        18
    3             5            null       2
100    1    null    8               null    null


Should it be recursive solution, have a friend who knows how to help solve it?

Code Universe replied 2 weeks ago

unfortunatelypythonNot familiar with, in fact, the algorithm is very simple. Intermediate traversal, each time the leaf node arrives to determine whether the sum is smaller than the previous calculation of the smallest sum, if so, update the minimum sum, the traversal completion of the results will come out.

7 Answers
Best Answer
Code Universe answered 2 weeks ago
huangzhuolin answered 2 weeks ago

Leetcode has a similar title, but it’s just a question of counting hops:https://leetcode.com/problems/minimum-depth-of-binary-tree/
This is minepythonImplement it. You can just change it a little.

class Solution(object):
    def minDepth(self, root):
        :type root: TreeNode
        :rtype: int
        if root is None:
            return 0
        if root.left is None:
            return 1 + self.minDepth(root.right)
        if root.right is None:
            return 1 + self.minDepth(root.left)
        return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
Fallenwood answered 2 weeks ago

I think it’s simple dp.

rqy answered 2 weeks ago

dynamic programmingThe introductory questions.

loop9 answered 2 weeks ago
def minPathSum(node):
    if not node:
        return 0
    return min(minPathSum(node.left), minPathSum(node.right)) + node.val
Chihiro Nangong answered 2 weeks ago

Give it a try with php, and you can seehttps://github.com/chianquan/Mytest/blob/master/shortest.php