using System;
using System.Collections.Generic;
public class Solution
{
public int RangeSumBST(TreeNode root, int low, int high)
{
// 「根節點」
var rootNode = root;
// 「下限值」(含)
var inclusiveLowerBound = low;
// 「上限值」(含)
var inclusiveUpperBound = high;
// 「節點佇列」
var nodeQueue = new Queue<TreeNode>();
// 「輸出值」
var output = 0;
nodeQueue.Enqueue(rootNode);
// 「節點」
TreeNode node;
while (nodeQueue.TryDequeue(out node))
{
if (node == null) { continue; }
// 「節點的數值」
var nodeValue = node.val;
if (inclusiveLowerBound <= nodeValue && nodeValue <= inclusiveUpperBound)
{
output += nodeValue;
}
nodeQueue.Enqueue(node.left);
nodeQueue.Enqueue(node.right);
}
return output;
}
}
https://leetcode.com/problems/range-sum-of-bst/
參考資料
上限、下限
https://en.wikipedia.org/wiki/Upper_and_lower_bounds
包含、不含
請參考「刷 LeetCode 練習命名」 https://github.com/EngTW/English-for-Programmers/issues/69 😊