leetcode-112. Path sum

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

answer:

 public boolean hasPathSum(TreeNode root, int sum) {

          if(root==null) return false;

        return cal(root, sum);

    }

      public boolean cal(TreeNode root, int sum){

        if(root.left==null){

            if(root.right==null){

                return sum-root.val==0;

            }else{

                return cal(root.right, sum-root.val);

            }

        }else{

            if(root.right==null){

                return cal(root.left, sum-root.val);

            }else{

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

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

                return left || right;

            }

        }

      }

Guess you like

Origin blog.csdn.net/wuqiqi1992/article/details/108344404