Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- kubernetes
- lambda
- Lamda
- IaC
- serverless
- Validation
- fcm
- aws
- rds
- CHECK
- terraform
- cloudwatch
- 병목
- amazonqcli
- sns
- SageMaker
Archives
- Today
- Total
잡다한 IT 지식
938.Range Sum of BST 본문
주어진 트리 노드에서 노드의 값을 val이라고 정의했을 때,
low <= node.val <= high 조건을 만족하는 값들의 총합을 구하시오.
[처음 푼 코틀린 코드]
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int {
var stack = Stack<TreeNode>()
stack.push(root)
//총합을 담을 변수.
var sum : Int = 0
while (!stack.empty()) {
var node = stack.pop()
sum += checkRange(stack,node,low,high)
}
return sum
}
fun checkRange(stack:Stack<TreeNode>, node:TreeNode, low:Int,high:Int) : Int {
//node의 값이 low와 high사이에 있으면 노드의 좌우를 null 체크하고 stack에 넣어줌.
if (low <= node.`val` && node.`val` <= high) {
if (node.left != null) {
stack.push(node.left)
}
if (node.right != null) {
stack.push(node.right)
}
return node.`val`
}
//node의 값이 low보다 작으면 left의 값이 node의 값보다 작기 때문에
//무조건 성립하지 않음.
//따라서 node의 값보다 큰 right만 stack에 넣어줌.
else if (node.`val` < low) {
if (node.right != null) {
stack.push(node.right)
}
}
//node의 값이 high보다 크면 right의 값이 node의 값보다 크기 때문에
//무조건 성립하지 않음.
//따라서 node의 값보다 작은 left만 stack에 넣어줌.
else if (high < node.`val` ) {
if (node.left != null) {
stack.push(node.left)
}
}
return 0
}
}
Null 처리하고 stack에 넣는 게 중복돼서 메소드로 분리했음.
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int {
var stack = Stack<TreeNode>()
stack.push(root)
var sum : Int = 0
while (!stack.empty()) {
var node = stack.pop()
sum += checkRange(stack,node,low,high)
}
return sum
}
fun checkRange(stack:Stack<TreeNode>, node:TreeNode, low:Int,high:Int) : Int {
if (low <= node.`val` && node.`val` <= high) {
nullCheckAndPush(stack, node.left)
nullCheckAndPush(stack, node.right)
return node.`val`
} else if (node.`val` < low) {
nullCheckAndPush(stack, node.right)
} else if (high < node.`val` ) {
nullCheckAndPush(stack, node.left)
}
return 0
}
//node가 null이 아니면 stack에 넣어줌.
fun nullCheckAndPush(stack:Stack<TreeNode>, node:TreeNode?) {
if (node != null) {
stack.push(node)
}
}
}
'알고리즘 문제 풀이 > DFS' 카테고리의 다른 글
백준 - 점프왕 쩰리 (못풀었다가 검토하다 다시 품) (0) | 2021.12.26 |
---|---|
프로그래머스 - 타겟 넘버 (0) | 2021.08.11 |
100. Same Tree (0) | 2021.08.10 |
94. Binary Tree Inorder Traversal (0) | 2021.08.09 |
589. N-ary Tree Preorder Traversal (0) | 2021.08.08 |