# 938. Range Sum of BST ## 題目概要 給定一個二元搜尋樹的節點和兩個整數 low 和 high,返回所有在 low ~ high 之間的節點總和。   ## 解題技巧 - 用遞迴的方式,判斷當前節點是不是介於 low, high 之間,如果是就 `sum += node.val`,然後繼續遍歷左、右子樹直到遍歷完所有節點。 ## 程式碼 ```javascript= /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @param {number} low * @param {number} high * @return {number} */ var rangeSumBST = function(root, low, high) { let sum = 0; const dfs = (node) => { if(!node) return; if(node.val >= low && node.val <= high) { sum += node.val; } dfs(node.left); dfs(node.right); } dfs(root); return sum; }; ``` 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up