[LeetCode] 173. Binary Search Tree Iterator, Medium

2025. 4. 10. 17:32·CodingTest/LeetCode
반응형

1. 문제

  • 이진 탐색 트리가 주어질 때, 중위 순회를 수행하여 요구사항을 만족하는 class를 구현하라.

2. 해결

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

class BSTIterator {
    pointer: number;
    travalArr: number[]
    constructor(root: TreeNode | null) {
        const traval = [];

        function DFS(node: TreeNode | null) {
            if(!node) return;
            
            DFS(node.left);
            traval.push(node.val);
            DFS(node.right);    
        }

        DFS(root);
        this.travalArr = traval;
        this.pointer = -1;
    }

    next(): number {
        return this.travalArr[++this.pointer];
    }

    hasNext(): boolean {
        return this.pointer + 1 < this.travalArr.length;
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * var obj = new BSTIterator(root)
 * var param_1 = obj.next()
 * var param_2 = obj.hasNext()
 */
  • 초기화 시점에 중위 순회를 통해 value를 배열에 담아두고, pointer는 -1로 초기화.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 701. Insert into a Binary Search Tree, Medium
  • [LeetCode] 700. Search in a Binary Search Tree, Easy
  • [LeetCode] 98. Validate Binary Search Tree, Medium
  • [LeetCode] 212. Word Search II, Hard
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준1427
    백준
    next 14
    medium
    boj1427
    백준7576자바
    meidum
    자바
    백준1260
    알고리즘
    프로그래머스
    leetcode 2236
    백준7576
    boj2108
    BOJ
    Easy
    Java
    component-scan
    백준2751
    TypeScript
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 173. Binary Search Tree Iterator, Medium
상단으로

티스토리툴바