Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 19046f9

Browse files
Add Solution2.java to problems 0938
1 parent 2a7c960 commit 19046f9

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
public int rangeSumBST(TreeNode root, int L, int R) {
12+
if (root == null) return 0;
13+
int sum = 0;
14+
Stack<TreeNode> stack = new Stack<>();
15+
while (true) {
16+
while (root != null) {
17+
stack.push(root);
18+
root = root.left;
19+
}
20+
if (stack.isEmpty()) break;
21+
22+
TreeNode node = stack.pop();
23+
if (node.val >= L && node.val <= R) {
24+
sum += node.val;
25+
}
26+
if (node.val > R) return sum;
27+
root = node.right;
28+
}
29+
return sum;
30+
}
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /