DWQA QuestionsCategory: ProgramAn algorithm problem that initializes a binary tree with Python and solves its shortest path value

Title:
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!
Examples:
If the input is 0 at the beginning of a line, the end of the input is indicated, and the empty node is null.

``````Input:
5
2       3
0

Output:
7

Input:
1
2                        18
3             5            null       2
100    1    null    8               null    null
0

Output:
7（1+2+3+1）``````

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

unfortunately`python`Not 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.

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 mine`python`Implement 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))
``````

I think it’s simple dp.

dynamic programmingThe introductory questions.

``````def minPathSum(node):
if not node:
return 0
return min(minPathSum(node.left), minPathSum(node.right)) + node.val``````

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