---
# System prepended metadata

title: Leetcode 104. Maximum Depth of Binary Tree
tags: [daily, DFS, leetcode]

---

# Leetcode 104. Maximum Depth of Binary Tree
###### tags: `leetcode` `daily` `DFS`

[題目連結](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/)

# Method 
:::info
:bulb: **作法講解**:
using DFS traversal all node,
initialize "level" to 0,
first traversal root node,set "level" to 1
when current node is NULL, return level - 1.
when current node not NULL, increase the "level", traversal left child of node, and right child of node.
:::

TC: O(N) SC: O(h)
:::spoiler 完整程式碼
```cpp=
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getMaxDepth(TreeNode* root, int level) 
    {
        if(root == NULL) {
            return level - 1;
        }
        level++;
        return max(getMaxDepth(root->left, level), getMaxDepth(root->right, level));
    }   
    int maxDepth(TreeNode* root) 
    {
        return getMaxDepth(root, 1);
    }
};
```
:::


