一:递归
/**
* 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 == NULL){
return 0;
}
int right = maxDepth(root->right);
int left = maxDepth(root->left);
return max(right, left) + 1;
}
};
二:广度优先遍历
/**
* 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 == NULL){
return 0;
}
int max_depth = 0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int s = q.size();
for(int i = 0; i < s; i++){
TreeNode* tmp = q.front();
q.pop();
if(tmp->left){
q.push(tmp->left);
}
if(tmp->right){
q.push(tmp->right);
}
}
max_depth++;
}
return max_depth;
}
};