题目链接:104. Maximum Depth of Binary Tree
C++
1.dfs
class Solution{
private:
int ans=0;
void def(TreeNode*root ,int depth){
if(root->left==NULL && root->left==NULL) ans=max(ans,depth);
if(root->left!=NULL) def(root->left,depth+1);
if(root->right!=NULL)def(root->right,depth+1);
}
public:
int maxDepth(TreeNode* root){
if(root==NULL)return 0;
ans=0;
def(root,1);
return ans;
}
};
2.递归简单版本(一行)
class Solution{
public:
int maxDepth(TreeNode* root){
return !root?0:max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
3.bfs
class Solution{
public:
int maxDepth(TreeNode* root){
if(!root)return 0;
queue<TreeNode*> q;
q.push(root);
int len = q.size(),ans=0;
TreeNode* temp;
while(q.size()){
ans++;
while(len--){
temp = q.front();
q.pop();
if(temp->left)q.push(temp->left);
if(temp->right)q.push(temp->right);
}
len = q.size();
}
return ans;
}
};
Python
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if(root==None):return 0
return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
来源:CSDN
作者:xxzccccccc
链接:https://blog.csdn.net/baidu_32048673/article/details/104137942