Leetcode Problem Solving path sum original problem
Determines whether a binary tree has a path from the root node to a leaf node, and is a specific value for all nodes on that path.
Note the point:
Example:
Input: sum = 12
3 9 20 / 15 7 / 14
Output: True (3->9)
Thinking of solving problems
Directly through the return solution, judge a node, first the value of the required values minus the value of the node, if the remaining required value is 0 and the current node is a leaf node, then the path from the root node to the current node to meet the requirements of the topic. Otherwise, the left and right nodes of the current node will continue to be recursive.
AC Source
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x):Self.val = x Self.left =NoneSelf.right =None class solution(object): def haspathsum(self, root, sum): "" : Type Root:TreeNode:type sum:int:rtype:bool "" " if notRootreturn FalseSum-= Root.valifsum = =0 andRoot.left is None andRoot.right is None:return True returnSelf.haspathsum (Root.left, sum)orSelf.haspathsum (root.right, sum)if__name__ = ="__main__":None
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Path Sum