# 104. Maximum Depth of Binary Tree

{% embed url="<https://leetcode.com/problems/maximum-depth-of-binary-tree/description/>" %}

> time: O(n)

> space: O(h)

```jsx
var maxDepth = function (root) {
    return find(root, 0);
};

function find(node, depth = 0) {
    if (node === null) return depth;
    depth++;
    return Math.max(find(node.left, depth), find(node.right, depth));
}
```

> time: O(n)

> space: O(n)

```javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    const q = [[root, 0]];

    let max = 0;
    while (q.length > 0) {
        const [node, cnt] = q.shift();
        if (node === null) continue;

        max = Math.max(cnt + 1, max);
        if (node.left !== null) q.push([node.left, cnt + 1]);
        if (node.right !== null) q.push([node.right, cnt + 1]);
    }

    return max;
};
```

> time: O(n)

> space: O(h) worst n skewed tree (편향 이진 트리)

```javascript
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */

function Track() {
    this.depth = 0;
}
const track = new Track();

var maxDepth = function(root) {
    track.depth = 0;
    findDepth(root, 0);
    return track.depth;
};

function findDepth(node, cnt = 0) {
    if (node === null) {
        track.depth = Math.max(track.depth, cnt);
        return;
    }

    cnt += 1;
    findDepth(node.left, cnt);
    findDepth(node.right, cnt);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/tree/104.-maximum-depth-of-binary-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
