题目描述
求给定二叉树的最大深度,
最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。
解题思路
/**
* Definition for binary tree
* 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 count = 0;
while(que.size() != 0){
int len = que.size();
for(int i = 0; i < len; i++){
TreeNode *p = que.front();
que.pop();
if(p->left)
que.push(p->left);
if(p->right)
que.push(p->right);
}
count++; //每经过一次循环,就说明走过了一层
}
return count;
}
};