How to solve the problem of path summation of leetcode trees
This article mainly introduces how to solve the leetcode tree path summation problem, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Given a binary tree and a goal sum, determine whether there is a path from the root node to the leaf node in the tree, and the value of all nodes on this path is equal to the goal sum. Note: a leaf node is a node that does not have child nodes. Example: given the following binary tree, and the target and sum = 22,5 /\ 48 / /\ 11 13 4 /\\ 7 21 returns true, because there is a path from the root node to the leaf node 5-> 4-> 11-> 2 for the target and 22. Source: LeetCode link: https://leetcode-cn.com/problems/path-sum copyright belongs to the collar buckle network. For commercial reprint, please contact official authorization. For non-commercial reprint, please indicate the source. Answer the question / Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} *} * / class Solution {public boolean hasPathSum (TreeNode root, int sum) {if (root = = null) {return false;} if (root.left = = null & & root.right = = null) {return sum-root.val = = 0 } return hasPathSum (root.left, sum-root.val) | | hasPathSum (root.right, sum-root.val);}} Thank you for reading this article carefully. I hope the article "how to solve the path Sum problem of leetcode trees" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!