path-sum

/**
* Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
* For example:
* Given the below binary tree andsum = 22,
* 5
* /
* 4 8
* / /
* 11 13 4
* /
* 7 2 1
* return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
*
* 给定一个二叉树和一个和,确定该树是否有一个根到叶的路径,以便将路径上的所有值相加等于给定的和。
* 例如:
* 如果下面的二叉树和和=22,
* 5
* /
* 4 8
* / /
* 11 13 4
* /
* 7 2 1
* 返回true,因为存在根到叶路径5->4->11->2,总和为22。
*/

/**
 * Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
 * For example:
 * Given the below binary tree andsum = 22,
 *               5
 *              / 
 *             4   8
 *            /   / 
 *           11  13  4
 *          /        
 *         7    2      1
 * return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.
 *
 * 给定一个二叉树和一个和,确定该树是否有一个根到叶的路径,以便将路径上的所有值相加等于给定的和。
 * 例如:
 * 如果下面的二叉树和和=22,
 *               5
 *              / 
 *             4   8
 *            /   / 
 *           11  13  4
 *          /        
 *         7    2      1
 * 返回true,因为存在根到叶路径5->4->11->2,总和为22。
 */

public class Main41 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);

        root.right = new TreeNode(8);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.right = new TreeNode(1);
        System.out.println(Main41.hasPathSum(root, 22));
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    public static boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
            if (sum == root.val) {
                return true;
            } else {
                return false;
            }
        }

        boolean left = hasPathSum(root.left, sum-root.val);
        boolean right = hasPathSum(root.right, sum-root.val);

        return left || right;
    }
}

  

原文地址:https://www.cnblogs.com/strive-19970713/p/11325597.html