iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

Leetcode30天挑戰系列 第 13

Day13-Path Sum

  • 分享至 

  • xImage
  •  

今天的題目為112.Path Sum,題目再叫我們判斷一棵二元樹中,是否存在一條從根節點到葉子節點的路徑,使得路徑上所有節點的值加總剛好等於targetSum。

以下是程式碼與解說:

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        // 若根節點為 null,代表空樹,無路徑可走
        if (root == null) return false;

        // 若是葉子節點,且值剛好等於 targetSum,則找到符合路徑
        if (root.left == null && root.right == null && root.val == targetSum) {
            return true;
        }

        // 遞迴檢查左右子樹,減去目前節點的值
        return hasPathSum(root.left, targetSum - root.val) ||
               hasPathSum(root.right, targetSum - root.val);
    }
}

今天的跟之前有一題蠻像的,都有差不多的概念。


上一篇
Day12-Minimum Depth of Binary Tree
下一篇
Day14-Path Sum II
系列文
Leetcode30天挑戰15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言