ð 112. è·¯åŸæ»å
2022幎10æ10æ¥
- algorithm
ð 112. è·¯åŸæ»å
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* 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) {
// æè·¯ïŒ
// å°ç¶èç¹çåŒå 诞äºå·Šå³åèç¹
return mySol(root, targetSum);
}
private boolean mySol(TreeNode root, int targetSum) {
// éåœç»æ¢æ¡ä»¶
if(root == null) {
return false;
}
if(root.left == null && root.right == null) {
if(root.val == targetSum) {
return true;
} else {
return false;
}
}
if(root.left != null) {
root.left.val += root.val;
}
if(root.right != null) {
root.right.val += root.val;
}
return mySol(root.left, targetSum) || mySol(root.right, targetSum);
}
}