首页 > 代码库 > Path Sum

Path Sum

题目:给定一颗二叉树以及一个sum,判断在二叉树中是否存在一条路径,使得路径上节点值之和等于sum

算法:深度优先搜索

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

Path Sum