二叉树的路径总和

原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/12145869.html

查询二叉树的路径之和是否等于一个给定的值!

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

    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }

        return hasPathS(root.left, root.right, root.val, sum);
    }

    public static boolean hasPathS(TreeNode left, TreeNode right,int pre, int sum){
        if (left == null && right == null) {
            return pre == sum;
        }
        if (left != null && right != null) {
            return hasPathS(left.left, left.right, pre + left.val, sum) || hasPathS(right.left, right.right, pre + right.val, sum);
        }
        if (left != null) {
            return hasPathS(left.left, left.right, pre + left.val, sum);
        }
        if (right != null) {
            return hasPathS(right.left, right.right, pre + right.val, sum);
        }

        return pre == sum;
    }
posted @ 2020-01-03 17:12  前往幸福的路上  阅读(471)  评论(0编辑  收藏  举报