Coding Interview

[LeetCode] BFS-DFS 104. Maximum Depth of Binary Tree

milliwonkim 2022. 9. 27. 17:30
반응형
SMALL

문제

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -100 <= Node.val <= 100

코드

// BFS
var maxDepth = function(root) {
    if(!root) return 0;
    const queue = [root];
    let max = 0;
    
    while(queue.length) {
        max = max + 1
        const length = queue.length;
        for(let i = 0; i < length; i++) {
            if(queue[i].left) queue.push(queue[i].left);
            if(queue[i].right) queue.push(queue[i].right);
        }
        queue.splice(0, length);
    }
    
    return max
};

// DFS
var maxDepth = function(root) {
    if (!root) return 0;
    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};
반응형
LIST