
😎풀이
TreeNode
를 연결형으로 조회할 수 있도록 LinkNode
클래스 생성
- 생성된
LinkNode
클래스에 TreeNode
를 전위순회 하며 알맞게 입력
- 입력된
LinkNode
클래스의 특성을 활용하여 다음 요소 확인 및 반환 메서드에 적절히 연결
class LinkNode {
value: number | null
next: LinkNode | null
constructor(value: number | null) {
this.value = value
}
}
class BSTIterator {
linkedList: LinkNode
constructor(root: TreeNode | null) {
this.linkedList = new LinkNode(null)
let mock = this.linkedList
function dfs(node: TreeNode | null) {
if(!node) return null
if(node.left) dfs(node.left)
const transferNode = new LinkNode(node.val)
mock.next = transferNode
mock = mock.next
if(node.right) dfs(node.right)
}
dfs(root)
}
next(): number {
this.linkedList = this.linkedList.next
return this.linkedList.value
}
hasNext(): boolean {
return !!this.linkedList.next
}
}