104. Maximum Depth of Binary Tree

来源:互联网 发布:mongodb是什么数据库 编辑:程序博客网 时间:2024/05/22 11:50

这里写图片描述
递归形式

    int maxDepth(TreeNode* root) {        if(!root) return 0;        return 1+max(maxDepth(root->left),maxDepth(root->right));    }

使用BFS

    int maxDepth(TreeNode* root) {        if(!root) return 0;        int res=0;        queue<TreeNode*> q;        q.push(root);        while(!q.empty()){            res++;            int n=q.size();            for(int i=0;i<n;i++){                TreeNode* t=q.front();q.pop();                if(t->left) q.push(t->left);                if(t->right) q.push(t->right);            }        }        return res;    }
原创粉丝点击