LeetCode 路径总和

版权声明:欢迎提问:[email protected] https://blog.csdn.net/include_heqile/article/details/82555946

https://leetcode-cn.com/problems/path-sum/description/

有一阵子没做LeetCode的题了

我的解决方案,题目很简单,没什么好讲解的,使用简单的递归即可:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean recursion(TreeNode root, int target) {
        if(root==null)
            return false;
        if(root.val==target)
            if(root.left==null&&root.right==null)
                return true;
        return recursion(root.left, target-root.val)==false?recursion(root.right, target-root.val):true;
    }
    public boolean hasPathSum(TreeNode root, int sum) {
        return root==null?false:recursion(root, sum);
    }
}

猜你喜欢

转载自blog.csdn.net/include_heqile/article/details/82555946