作者:whisper
链接:https://www.proprogrammar.com/article/872
声明:请尊重原作者的劳动,如需转载请注明出处
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
难度:简单;标签:树,深度优先搜索;编程语言:C++
/**
* 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) {
return !root ? 0 : 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
一行代码,左右最大深度+1(1是当前节点+1深度)
/**
* 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){
// return 0;
// }
// return (max(maxDepth(root->left),maxDepth(root->right))+1);
if(!root){
return 0;
}
queue<TreeNode*> qu;
qu.push(root);
TreeNode *p=NULL;
int height=0;
while(qu.size()>0){
int size=qu.size();
height++;
for(int i=0;i<size;i++){
p=qu.front();
qu.pop();
if(p->left){
qu.push(p->left);
}
if(p->right){
qu.push(p->right);
}
}
}
return height;
}
};
这里是用队列的bfs解法,一层层+1,可以学一下bfs的解题模板
亲爱的读者:有时间可以点赞评论一下
全部评论