rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

112. 路径总和 #68

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) return false;
        return traversal(root, targetSum - root.val);
    }
    private boolean traversal(TreeNode root, int count){
        if(root.left == null && root.right == null && count == 0) return true;
        if(root.left == null && root.right == null) return false;
        if(root.left != null){
            if(traversal(root.left, count - root.left.val)) return true;
        }
        if(root.right != null){
            if(traversal(root.right, count - root.right.val)) return true;
        }
        return false;
    }
}
rocksc30 commented 1 year ago
  1. 路径总和 II

    /**
    * Definition for a binary tree node.
    * public class TreeNode {
    *     int val;
    *     TreeNode left;
    *     TreeNode right;
    *     TreeNode() {}
    *     TreeNode(int val) { this.val = val; }
    *     TreeNode(int val, TreeNode left, TreeNode right) {
    *         this.val = val;
    *         this.left = left;
    *         this.right = right;
    *     }
    * }
    */
    class Solution {
    private List<List<Integer>> ans = new ArrayList<>();
    private Stack<Integer> path = new Stack<>();
    
    private void traveral(TreeNode root, int count){
        if (root.left == null && root.right == null && count == 0) {
            ans.add(new ArrayList(path));
            return;
        }
        if (root.left == null && root.right == null) {
            return;
        }
        if (root.left != null) {
            path.push(root.left.val);
            traveral(root.left, count - root.left.val);
            path.pop();
        }  
        if (root.right != null) {
            path.push(root.right.val);
            traveral(root.right, count - root.right.val);
            path.pop();
        }  
    }
    
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return ans;
        }
        path.push(root.val);
        traveral(root, targetSum - root.val);
        return ans;
    }
    }