[LeetCode] 111. Minimum Depth of Binary Tree

Lucid·2021년 2월 25일
1
post-thumbnail

문제

https://leetcode.com/problems/minimum-depth-of-binary-tree/

문제 접근 및 풀이

생각한 데로 쫙 작성하고 run 하니까 딱 됐는데 submit하니까 안됐다!!
null 이라면 1001값을 반환하도록 구성했는데 (최댓값을value로 착각해서 조건을 잘못봤음) 잘못 본 것을 찾는게 문제 푸는 것보다 오래 걸렸다 ㅎㅎ
MAX 값만 수정해주니 처음 생각한 알고리즘에 딱 맞아서 너무 행복 ㅎㅎ

간단 슈도코드

// 내가 null인가? return MAX 마지막에 MAX값이면 1 반환하자
// 내 자식들이 null 인가? return depth (내가 leaf 노드인 것)
// left와 right 탐색해서 min 값 찾아서 return 해주자

결과

const MAX = Math.pow(10, 5) + 1;

const searchMinDepth = (root, depth) => {
  if (root === null) return MAX;
  depth++;

  if (root.left === null && root.right === null) return depth;

  const leftMin = searchMinDepth(root.left, depth);
  const rightMin = searchMinDepth(root.right, depth);

  const min = Math.min(leftMin, rightMin);
  return min;
};

const minDepth = (root) => {
  if (root === null) return 0;
  const value = searchMinDepth(root, 0);
  return value === MAX ? 1 : value;
};

사담

이번주는 dfs 조지기! 다음주는 bfs 조지기!
그리고 프로그래머스로 넘어가야지

profile
Find The Best Solution 😎

0개의 댓글