解法一:递归:
/**
* 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 left = root->left ? maxDepth(root->left) : 0;
int right = root->right ? maxDepth(root->right) : 0;
return max(left, right) + 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;
queue<vector<TreeNode*>> q;
vector<TreeNode*> cur;
cur.push_back(root);
q.push(cur);
int ans = 0;
while(!q.empty()){
vector<TreeNode*> list = q.front();
q.pop();
vector<TreeNode*> tmp;
ans++;
cout<<ans<<endl;
for(int i = 0; i < list.size();i++){
if(list[i]->left) tmp.push_back(list[i]->left);
if(list[i]->right) tmp.push_back(list[i]->right);
}
if(tmp.size()) q.push(tmp);
}
return ans;
}
};