[LeetCode] 104. Maximum Depth of Binary Tree

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

문제

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

문제 접근 및 풀이

count 변수를 두어서 dfs를 호출할 때마다 +를 해주어야겠다고 생각하고 알고리즘을 생각해보았다.
하지만 내가 생각한대로 처리를 하게 되면 왼쪽과 오른쪽 노드의 depth를 확인할 때마다 count변수가 의미없이 높아지게 되었다..
사실 어쨌든 이 문제는 depth만을 확인해주면 된다. 더 깊은 값을 계속해서 선택해주면 된다. (dfs)
그래서 파라미터로 depth값을 주고 search 할 때마다 max값을 비교하여 max값을 return하는 방식으로 처리했다.

결과

const searchDepth = (node, depth) => {
    if(node === null) return depth;
    depth++;
    
    const leftDepth = searchDepth(node.left, depth);
    const rightDepth = searchDepth(node.right, depth);
    
    const max = Math.max(leftDepth, rightDepth);
    return max;
}

const maxDepth = (root) => {
    return searchDepth(root,0);
};
profile
Find The Best Solution 😎

0개의 댓글