Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.A leaf is a node with no children. Example 1:Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22Output: trueExplanation: The root-to-leaf path with the target sum is shown.Example 2:Input: root = [1,2,3], targetSum = 5Output: falseExplanation: There two root-to-leaf paths in the tree:(1 --> 2): The sum is 3.(1 --> 3): The sum is 4.There is no root-to-leaf path with sum = 5.Example 3:Input: root = [], targetSum = 0Output: falseExplanation: Since the tree is empty, there are no root-to-leaf paths. Constraints:The number of nodes in the tree is in the range [0, 5000].-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
Question
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.A leaf is a node with no children. Example 1:Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22Output: trueExplanation: The root-to-leaf path with the target sum is shown.Example 2:Input: root = [1,2,3], targetSum = 5Output: falseExplanation: There two root-to-leaf paths in the tree:(1 --> 2): The sum is 3.(1 --> 3): The sum is 4.There is no root-to-leaf path with sum = 5.Example 3:Input: root = [], targetSum = 0Output: falseExplanation: Since the tree is empty, there are no root-to-leaf paths. Constraints:The number of nodes in the tree is in the range [0, 5000].-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
Solution
This problem is a classic example of a depth-first search (DFS) problem in a binary tree. Here's a step-by-step solution:
- First, we need to handle the base case. If
Similar Questions
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Given the root of a binary tree, return the sum of all left leaves.A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
Given a Binary Tree of size N, your task is to complete the function rightLeafSum(), which should return the sum of all the leaf nodes that are the right child of their parent of the given binary tree.
whether all of its nodes have the value equal to the sum of their child nodes.
In a full binary tree if number of internal nodes is I, then number of leaves L are?OptionsL = 2*IL = I + 1 L = I – 1L = 2*I – 1
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.