์ฝ๋
class Solution {
public int rangeSumBSTDFS(TreeNode root, int low, int high) {
// ํ์ ๋
ธ๋ ์์ผ๋ฉด ์ข
๋ฃ
if (root == null) {
return 0;
}
// ํ์ฌ ๋
ธ๋์ ๊ฐ์ด high๋ณด๋ค ํฌ๋ค๋ฉด, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ํ์ํ ํ์ ์์
if (root.val > high) {
return rangeSumBST(root.left, low, high);
}
// ํ์ฌ ๋
ธ๋์ ๊ฐ์ด low๋ณด๋ค ์๋ค๋ฉด, ์ผ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ํ์ํ ํ์ ์์
if (root.val < low) {
return rangeSumBST(root.right, low, high);
}
// ํ์ฌ ๋
ธ๋์ ๊ฐ์ด [low, high] ๋ฒ์์ ์๋ ๊ฒฝ์ฐ:
// ํ์ฌ ๋
ธ๋์ ๊ฐ์ ๋ํ๊ณ , ์ผ์ชฝ ๋ฐ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ ๋ชจ๋ ํ์
return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
}
}
Java
๋ณต์ฌ
class Solution {
public int rangeSumBSTBFS(TreeNode root, int low, int high) {
if (root == null) {
return 0;
}
int sum = 0;
Deque<TreeNode> queue = new ArrayDeque<>();
// BFS๋ ์์ ๋
ธ๋๋ฅผ ๋ฏธ๋ฆฌ ํ์ ์ถ๊ฐํ๊ณ ํ์ ์์.
queue.add(root);
while (!queue.isEmpty()) {
// ์ต์์ ๋
ธ๋๋ถํฐ ํ์ ์์
TreeNode node = queue.poll();
if (node != null) {
// ๋ฒ์ ์กฐ๊ฑด ๋ง์กฑํ๋ฉด ํฉ์ฐํด์ ๊ฒฐ๊ณผ๊ฐ์ ์ถ๊ฐ
if (node.val >= low && node.val <= high) {
sum += node.val;
}
// ํ์ฌ ๋
ธ๋์ ๊ฐ์ด low๋ณด๋ค ํฌ๋ค๋ฉด, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ํ์ํ ํ์ ์์
if (node.val > low) {
queue.add(node.left);
}
// ํ์ฌ ๋
ธ๋์ ๊ฐ์ด high๋ณด๋ค ์๋ค๋ฉด, ์ผ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ํ์ํ ํ์ ์์
if (node.val < high) {
queue.add(node.right);
}
}
}
return sum;
}
}
Java
๋ณต์ฌ
๋ฌธ์ ํด๊ฒฐ ์์ด๋์ด
์ฌ๊ท๋ฅผ ํ์ฉํ DFS ๊ตฌ์กฐ๋ก ์กฐ๊ฑด์ ๋ง๋ ๋
ธ๋๋ฅผ ํ์ํ๊ฑฐ๋, BFS์ ๋ฐ๋ณต ๊ตฌ์กฐ๋ฅผ ํ์ฉํด์ ์กฐ๊ฑด์ ๋ง๋ ๊ฒฐ๊ณผ๋ฅผ ๊ตฌํ๋ค.