-
Notifications
You must be signed in to change notification settings - Fork 4
/
938.Range_Sum_of_BST.js
46 lines (46 loc) · 1009 Bytes
/
938.Range_Sum_of_BST.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* 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 calculateSum = (node) => {
if (node) {
if (node.val >= low && node.val <= high) {
sum += node.val;
}
calculateSum(node.left);
calculateSum(node.right);
}
};
calculateSum(root);
return sum;
// 栈
let sum = 0;
const stack = [];
if (root) stack.push(root);
while (stack.length) {
const node = stack.pop();
if (node.val >= low && node.val <= high) {
sum += node.val;
}
if (node.left) {
stack.unshift(node.left);
}
if (node.right) {
stack.unshift(node.right);
}
}
return sum;
};