递归法
/**
* 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 leftDepth=maxDepth(root->left)+1;
int rightDepth=maxDepth(root->right)+1;
return max(leftDepth,rightDepth);
}
};
非递归,层次遍历
/**
* 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 depth=0;
queue<TreeNode*> que;
TreeNode* cur = root;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i=0; i<size; ++i){
cur = que.front();
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
++depth;
}
return depth;
}
};