LeetCode 112. 路径总和

91 阅读1分钟

image.png

递归法

递归函数:hasPathSum(node.child, sum - node.value)

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        if (root.val == sum && root.left == null && root.right == null) {//1.当前节点value=sum 2.当前节点为叶子节点
            return true;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}