---
description: Binary tree, level order traversal
---

# 104. Maximum Depth of Binary Tree

## 1.問題

* 給予一個binary tree, 找出最大的深度
* **最大的深度**是指**可到最遠的leaf node的子樹的長度**
* Note: leaf是指沒有children的node

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LGtq-zPUB8W5o4XdtB7%2F-LGts3plCyx4W2ZZYoXC%2F2018070803.jpg?alt=media\&token=f013f345-53db-489e-a6e8-d83ded72bebb)

## 2.想法

* 提問
  * 確認題意
* function header, parameter
* test input
* 說明想法
  * 最底層(NULL)視為-1層, 以此類推
* 測試計算複雜度

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) {
            return 0;
        }
        return findDepth(root);
    }
private:
    int findDepth(TreeNode* root) {
        if (!root) {
            return 0;
        }
        
        return max(findDepth(root->left), findDepth(root->right)) + 1;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LGtq-zPUB8W5o4XdtB7%2F-LGtxhTrZe1p_iNDgLa3%2F2018070804.jpg?alt=media\&token=3243037b-98a2-476f-a0d9-c2efc7663932)
