此篇文章為我的解題紀錄,程式碼或許並不是很完善

Leetcode - 104. Maximum Depth of Binary Tree

解題思路

使用recursive算樹的深度,若是有子節點則再次呼叫函式並把自己的子節點傳進去,並從左右子節點內挑出最大深度

我滴程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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;
}
else
{
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
}
};