104. Maximum Depth of Binary Tree

|▌冷眼眸甩不掉的悲伤 提交于 2020-02-02 04:57:48

题目链接: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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!