---
# System prepended metadata

title: Question 104. Maximum Depth of Binary Tree
tags: [leetcode]

---

###### tags: `leetcode`
# Question 104. Maximum Depth of Binary Tree
### Description:
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.
### Solution:
Two solution:
- DFS
    - Deep First Search:
        - bottom up
        - Recursive
- BFS
    - Breadth First Search
        - top down
        - Use Queue
### AC code
Code 1, DFS
```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:
    //DFS
    int maxDepth(TreeNode* root) {
        if(root==NULL)
            return 0;
        return (max(maxDepth(root->left), maxDepth(root->right))+1);
    }
```
code 2, BFS
```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:
    //BFS
    int maxDepth(TreeNode* root) {
        if(root==NULL)
            return 0;
        int ret = 0;
        queue<TreeNode*> r;
        r.push(root);
        while(!r.empty()){
            ++ret;
            int n = r.size();
            for(int i = 0 ; i < n ; i++){
                TreeNode* tmp = r.front();
                r.pop();
                if(tmp->left!=NULL)
                    r.push(tmp->left);
                if(tmp->right!=NULL)
                    r.push(tmp->right);
            }
        }
        return ret;
    }
};
```