112. 路径总和

深度优先搜索

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {

        /**
         * 递归终止条件
         * 节点为空时返回false
         * 节点没有孩子,剩余的数值等于节点值时返回true
         */
        if (root == null){
            return false;
        }

        if (root.left == null && root.right == null){
            return targetSum == root.val;
        }

        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

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

posted @ 2021-10-27 20:09  振袖秋枫问红叶  阅读(28)  评论(0)    收藏  举报