LeetCode #112 Path Sum 路徑總和

英文原文如下

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

中文翻譯

給予一棵二元樹的父節點,以及一個整數 targetSum,要是這棵樹有一條從父到葉節點的路徑總和等於targetSum的話就回傳true。

一個葉節點代表該節點沒有子節點。

範例及題目限制

限制:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

解題思路

在這一題中,我們可以使用一個簡單的遞迴來實作DFS (Depth-First-Search 深度優先搜尋)這種演算法。

該演算法會盡可能深的探索樹的分支。

C# 解決方案

方案1

public class Solution {
    public bool HasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }

        //minus value of current node
        targetSum -= root.val;
        
        //check if now a leaf node
        if (root.left == null && root.right == null) {
            return targetSum == 0;
        }

        return HasPathSum(root.left, targetSum) || HasPathSum(root.right, targetSum);
    }
}

在遞迴中,我們會將目標值減去當前節點的值再判斷是否為葉節點,要是的話會判斷目標值是否剩0。

不是的話就會針對左節點以及右節點繼續向下搜尋。

Java解決方案

方案1

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }

        //minus value of current node
        targetSum -= root.val;
        
        //check if now a leaf node
        if (root.left == null && root.right == null) {
            return targetSum == 0;
        }

        return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
    }
}

Python3 解決方案

方案1

class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if(root==None):
            return False
        
        #minus value of current node
        targetSum = targetSum-root.val
        
        #check if now a leaf node
        if (root.left == None and root.right == None):
            return targetSum == 0
        
        return self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)

JavaScript 解決方案

方案1

var hasPathSum = function(root, targetSum) {
    if (root == null) {
        return false;
    }

    //minus value of current node
    targetSum -= root.val;
    
    //check if now a leaf node
    if (root.left == null && root.right == null) {
        return targetSum == 0;
    }

    return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
};

結論

DFS是一個常用於遍歷整棵二元樹的簡單演算法,必須要好好做個筆記~

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Path Sum – LeetCode

一些隨機的LeetCode文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *