112.路径总和

张开发
2026/4/15 14:44:18 15 分钟阅读

分享文章

112.路径总和
package org.example; class Solution { public boolean hasPathSum(TreeNode root, int targetSum) { if (root null) { return false; } else { return traversal(root, targetSum - root.val); } } /** * 检查根结点到叶子结点的路径总和是否等于目标值 * * param root 根结点 * param targetSum 目标值 * return 路径总和等于目标值则返回 true否则则返回 false */ private boolean traversal(TreeNode root, int targetSum) { if (root.left null root.right null targetSum 0) { // 到达叶子结点且目标值等于 0 return true; } else if (root.left null root.right null targetSum ! 0) { // 到达叶子结点但是目标值不等于 0 return false; } else { // 没有到达叶子结点 // 则继续检查 // 检查左子树 if (root.left ! null traversal(root.left, targetSum - root.left.val)) { return true; } // 检查右子树 if (root.right ! null traversal(root.right, targetSum - root.right.val)) { return true; } return false; } } }

更多文章