leetcode-112.路径总和

题目:https://leetcode-cn.com/problems/path-sum/

答案:

 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;

            }

        }

      }

猜你喜欢

转载自blog.csdn.net/wuqiqi1992/article/details/108344404
今日推荐