(1)递归遍历
/**
* 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 {
private:
int maxs=0;
public:
void helper(TreeNode *root,int h) {
if(!root) return;
if(maxs<h) maxs=h;
helper(root->left,h+1);
helper(root->right,h+1);
return;
}
int maxDepth(TreeNode* root) {
helper(root,1);
return maxs;
}
};