求树的深度,比较简单;
可以通过先根遍历(类似于二叉树的深度优先遍历),或者广度优先中最后一个节点的深度即为树的深度;
class Solution {
public:
int maxdepth = 0;
int maxDepth(TreeNode *root) {
if(root == NULL){
return 0;
}
preOrder(root,1);
return maxdepth;
}
void preOrder(TreeNode *root,int depth)
{
if(depth > maxdepth){
maxdepth = depth;
}
if(root->left != NULL){
preOrder(root->left,depth+1);
}
if(root->right != NULL){
preOrder(root->right,depth+1);
}
}
};
class Solution {
public:
int maxdepth = 0;
int maxDepth(TreeNode *root) {
if(root == NULL){
return 0;
}
queue<TreeNode*> q;
map<TreeNode*,int> depth;
q.push(root);
depth[root] = 1;
while(q.size() != 0){
if(q.front()->left != NULL){
q.push(q.front()->left);
depth[q.front()->left] = depth[q.front()] + 1;
}
if(q.front()->right != NULL){
q.push(q.front()->right);
depth[q.front()->right] = depth[q.front()] + 1;
}
if(q.size()>1){
q.pop();
}
else{
return depth[q.front()];
}
}
}
};