---
# System prepended metadata

title: 'Leetcode : 0104. Maximum Depth of Binary Tree (Tree)'
tags: [leetcode]

---

# Leetcode : 0104. Maximum Depth of Binary Tree (Tree)
###### tags:`leetcode`
> DFS methods
```

class Solution01 {
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0; // if node null , have not value next node.
        int maxLeft = maxDepth(root->left); //check left value 
        int maxRight = maxDepth(root->right); //check right value
        return 1 + max(maxLeft, maxRight); //have value count + 1 , and recursive left and right.
    }
};

//DFS methods

/* example
              3
             / \
            9   20
                / \
               15   7
                   
*/

// left depth
//  9 -> left  = null
//  9 -> right = null
// return 1 + max(0,0); //add self 9

// right depth
// 15 -> left  = null : return 0;
// 15 -> right = null : return 0;
// return 1 + max(0,0); //add self 15 ----
//                                       |   
//  7 -> left  = null : return 0;        |
//  7 -> right = null : return 0;        |
// return 1 + max(0,0); //add self 7---  |
//                                    |  |               
// 20 -> left  = 15 : return 1;       |  |
// 20 -> right = 7  : return 1;       |  |
// return 1 + max(1,1) //add self 20  |  |
//                ↑                   |  |
//                --------------------|  |
//                  ↑                    |
//                  ---------------------|
// back main root
// root = 3
//  3 -> left  =  9 : return 1;
//  3 -> right = 20 : return 2;
// return 1 + max(1,2) //add self 3

// get answer = 3

```


> BFS methods

```
/**
 * 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 maxDepth(TreeNode* root) {
        if (root==NULL) return 0; 
        queue<TreeNode*> q;
        q.push(root);
        int depth=0;
        
        while (!q.empty()) {
            ++depth;
            int s=q.size();
            for (int i=0; i<s; i++) {
                TreeNode* front=q.front(); //save tmp head have left and right.
                q.pop(); 
                
                if (front->left) q.push(front->left);   // next tree-left 
                if (front->right) q.push(front->right); // next tree-right
                //if next left and right is null , check not next depth
            }
        }
    return depth;
    }
};
```
