题解 | #二叉树的深度#

二叉树的深度

http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b

struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
//使用bfs层次遍历求解深度
class Solution {
public:
    int TreeDepth(TreeNode* pRoot) {
            if(!pRoot)return 0;//如果为空直接返回0
        queue<TreeNode*>tree;
        int depth=0;
        tree.push(pRoot);
        while(!tree.empty()){
            int size=tree.size();//通过队列每次只遍历一层
            while(size--){
                TreeNode* temp=tree.front();//队首出队
                tree.pop();
                if(temp->left!=NULL)
                tree.push(temp->left);
                if(temp->right!=NULL)
                tree.push(temp->right);
            }
            depth+=1;
        }
        return depth;
    }
};
全部评论

相关推荐

05-16 11:16
已编辑
东华理工大学 Java
牛客737698141号:盲猜几十人小公司,庙小妖风大,咋不叫她去4️⃣呢😁
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务