Practice28:
/*
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)return 0;
queue<TreeNode*> pq;
pq.push(pRoot);
int level=0;
while(!pq.empty()){
int size = pq.size();
while(size--){
TreeNode* mid = pq.front();
pq.pop();
if(mid->left)pq.push(mid->left);
if(mid->right)pq.push(mid->right);
}
++level;
}
return level;
}
};
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
S1
分而治之法
/*
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)return 0;
int lval = TreeDepth(pRoot->left);
int rval = TreeDepth(pRoot->right);
return max(lval,rval)+1;
}
};
S2
队列遍历法
这篇博客介绍了计算二叉树深度的两种方法:分而治之(递归)和队列遍历。递归方法通过分别计算左右子树的深度并取最大值加一得到树的深度;队列遍历方法利用层次遍历,逐层扩大队列,直到队列为空,返回层次数即为树的深度。
形成树的一条路径,最长路径的长度为树的深度&spm=1001.2101.3001.5002&articleId=110881091&d=1&t=3&u=2c5b7cf6db0b436c8c02bdf3146caa82)
1061

被折叠的 条评论
为什么被折叠?



