let 112. Path Sum

主题思想: 判断是否存在一条根节点到叶子节点的路径,路径上的和等于指定数值。

AC 代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {

        if(root==null) return false;

        return findPathSum(root,0,sum);
    }

    public boolean findPathSum(TreeNode root,int tmp, int sum){

        if(root==null) return false;

         if(root.left==null&&root.right==null){
             return (tmp+root.val)==sum;
         }

        return findPathSum(root.left,tmp+root.val,sum)||findPathSum(root.right,tmp+root.val,sum);

    }

}

猜你喜欢

转载自blog.csdn.net/the_conquer_zzy/article/details/79200660