leetcode104题,计算二叉树的深度。
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.
第一种方法采用递归,以遍历到最底层叶节点为返回条件,每个父节点得到自己左右子树之中深度大者,将结果+1返回给上一层。
int maxDepth(strut TreeNode * root)
{
if (root == NULL)
{
return 0;
}
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return left > right ? left + 1 : right + 1;
}
第二种方法使用c++中的队列容器,使用一个int型变量来记录当前层是否遍历完,如果遍历完,深度+1,否则继续遍历当前层。
int maxDepth1(struct TreeNode * root)
{
if (NULL == root)
{
return 0;
}
queue<TreeNode*> que;
int count = 1;
int treedepth = 0;
que.push(root);
while (!que.empty())
{
TreeNode * temp = que.front();
que.pop();
if (temp->left)
que.push(temp->left);
if (temp->right)
que.push(temp->right);
count--;
if (count == 0)
{
treedepth++;
count = que.size();
}
}
return treedepth;
}