Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions kth-smallest-element-in-a-bst/delight010.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
// Time O(k)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

왜 시간복잡도가 O(k)라고 생각하셨는지 궁금합니다..!! k=1이고 왼쪽으로 치우쳐진 트리라면 제일 밑단까지 내려가기 위해 시간이 더 걸리지 않을까 싶어서요!

// Space O(height of Tree)
func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int {
var count = 0
var result = root!.val

inorderTree(root, &count, k, &result)

return result
}

private func inorderTree(_ node: TreeNode?, _ count: inout Int, _ k: Int, _ result: inout Int) {
guard let node = node else { return }
if count == k { return }

// left search
inorderTree(node.left, &count, k, &result)

// current node
count += 1
if count == k {
result = node.val
return
}

// right search
inorderTree(node.right, &count, k, &result)
}
}