LeetCode 437. Path Sum III — JavaScript

希望能夠好天氣~準備爬南湖了
var pathSum = function(root, sum) {
if (!root) return 0
return (
pathSumStart(root, sum) +
pathSum(root.left, sum) +
pathSum(root.right, sum)
)
};
const pathSumStart = (root, sum) => {
if (!root) return 0;
const self = root.val === sum ? 1 : 0;
return (
self +
pathSumStart(root.left, sum - root.val) +
pathSumStart(root.right, sum - root.val)
)
}

如果子 node.val 等於 sum 減 root.val 就符合目標 sum,例如 現在 root.val = 5,sum = 8,當子 node.val = 5 即符合題目需求。因此只要將每一個 node 當作 root,幾算延伸出去的 path 是否符合 sum 即可

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
黃韋智

自學寫程式,目前爲 React 前端工程師。熱愛旅遊,將近 30 個國家,足跡遍佈亞洲與歐洲。生命與街舞已經離不開,歡迎訂閱 Youtube 頻道:https://www.youtube.com/channel/UCEU-bEDl7R-iGyLVZFae33g