Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
我借鉴的代码(非递归实现)
/**
* Definition for a binary tree node.
* 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;
}
else
{
queue<TreeNode *> que;
que.push(root);
int depth = 0;
int count;
TreeNode *left, *right;
while(que.empty() == false)
{
depth++;
count = que.size();
for(int i=0;i<count;i++)
{
left = que.front()->left;
if(left)
{
que.push(left);
}
right = que.front()->right;
if(right)
{
que.push(right);
}
que.pop();
}
}
return depth;
}
}
};
递归实现:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
{
return 0;
}
else
{
int depth1 = maxDepth(root->left);
int depth2 = maxDepth(root->right);
if(depth1>depth2)
{
return depth1 + 1;
}
else
{
return depth2 + 1;
}
}
}
};