[LeetCode] 331. Verify Preorder Serialization of a Binary Tree

Chobby·2025년 3월 16일
1

LeetCode

목록 보기
294/427

😎풀이

  1. ,를 기준으로 preorder 분리
  2. leaf노드를 확인할 slot 선언
  3. nodes를 순회
    3-1. leaf노드가 중간에 끊겼다면 false 반환
    3-2. #가 발견 됐다면, leaf --
    3-3. 숫자가 발견될 경우 leaf가 감소하지만 자식 leaf가 2개 늘어남
  4. 이진 트리가 잘 구성되었는지 여부 반환
function isValidSerialization(preorder: string): boolean {
    const nodes = preorder.split(",")
    let slot = 1
    for(const node of nodes) {
        if(slot === 0) return false
        if(node === '#') slot--
        else slot = slot - 1 + 2
    }
    return slot === 0
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글