剑指offer_编程题_二叉树的深度
其他
2020-04-27 18:39:13
阅读次数: 0
- 递归方式,求子树的最大高度+1
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if (pRoot==NULL)
{
return 0;
}
return TreeDepth(pRoot->left)>TreeDepth(pRoot->right)?TreeDepth(pRoot->left)+1:TreeDepth(pRoot->right)+1;
}
};
- 非递归,层次遍历
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if (pRoot==NULL)
{
return 0;
}
std::queue<TreeNode*> q;
int length, high=0;
q.push(pRoot);
length = q.size();
while(length!=0){
for (int i = 0; i < length; ++i)
{
TreeNode* temp = q.front();
q.pop();
if (temp->left!=NULL) q.push(temp->left);
if (temp->right!=NULL) q.push(temp->right);
}
high += 1;
length = q.size();
}
return high;
}
};
发布了80 篇原创文章 ·
获赞 18 ·
访问量 1万+
转载自blog.csdn.net/C_abua/article/details/105704486