[leetcode][js] 104번

Dev.Jo·2021년 12월 8일
1

알고리즘

목록 보기
2/21
post-thumbnail
  1. Maximum Depth of Binary Tree

이진트리의 최대 깊이 (높이)

풀이

var maxDepth = function (root) {
    if(root===null){
        return 0;
    }
  return Math.max(dfs(root.left, 1), dfs(root.right, 1));
};

function dfs(root, count) {
  if (root === null) {
    return count;
  }
  return Math.max(dfs(root.left, count + 1),dfs(root.right, count + 1));
}
  • DFS를 이용하여 부모의 왼쪽자식, 오른쪽자식을 재귀적으로 탐색.
  • 왼쪽자식의 높이와 오른쪽자식의 높이중 큰것을 return
  • 해당 노드가 없는경우 (root===null) 이때까지의 높이를 return 한다

예외케이스

  • root 자체가 []로 빈 배열인 경우를 생각해줘야 root.left , root.right를 읽을 수 있음
profile
소프트웨어 엔지니어, 프론트엔드 개발자

0개의 댓글