递归比较
/**
* 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 sum_max;
sum_max=max(maxDepth(root->left),maxDepth(root->right))+1;
return sum_max;
}
};
BFS层序遍历
队列里保存当前层的节点数,每次向下拓展完毕(sz=0),ans++,最终返回ans为深度。
/**
* 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<TreeNode*> que;
que.push(root);
int ans=0;
while(!que.empty())
{
int sz=que.size();
while(sz>0)//当前层还有没有拓展的节点
{
TreeNode* node=que.front();
que.pop();
if(node->left)
que.push(node->left);
if(node->right)
que.push(node->right);
sz--;
}
ans++;
}
return ans;
}
};