104. 二叉树的最大深度
文章链接:代码随想录 (programmercarl.com)
视频链接:二叉树的高度和深度有啥区别?究竟用什么遍历顺序?很多录友搞不懂 | LeetCode:104.二叉树的最大深度_哔哩哔哩_bilibili
笔记
- 非递归方法可以用层序遍历
- 深度:到根节点的距离(前序遍历);高度:到叶子节点的距离(后序遍历)
C++代码
class Solution {
public:
int getDepth(TreeNode* root){
if(root==nullptr)return 0;
int depl=1+getDepth(root->left);
int depr=1+getDepth(root->right);
return depl > depr ? depl : depr;
}
int maxDepth(TreeNode* root) {
int dep=getDepth(root);
return dep;
}
};
559. N 叉树的最大深度
笔记
- 同上,能解出来,但总感觉哪里怪怪的
C++代码
class Solution {
public:
int res=0;
void pre(Node* root,int depth){
res=res>depth?res:depth;
for(Node* child: root->children){
depth++;
pre(child,depth);
depth--;
}
}
int maxDepth(Node* root) {
if(root){
pre(root,1);
}
return res;
}
};
111. 二叉树的最小深度
笔记
- 本题求的是最小深度,只有当左右孩子均是空的时候才能返回正确的最小深度,按照上题的写法,会误判没有左子树或右子树的根节点的深度为1.
C++代码
class Solution {
public:
int getDepth(TreeNode* root){
if(root==nullptr)return 0;
int depl=getDepth(root->left)+1;
int depr=getDepth(root->right)+1;
if(root->left==nullptr && root->right!=nullptr){
return depr;
}
if(root->left!=nullptr && root->right==nullptr){
return depl;
}
int res=min(depl,depr);
return res;
}
int minDepth(TreeNode* root) {
int depth=getDepth(root);
return depth;
}
};
222. 完全二叉树的节点个数
文章链接:代码随想录 (programmercarl.com)
视频链接:要理解普通二叉树和完全二叉树的区别! | LeetCode:222.完全二叉树节点的数量_哔哩哔哩_bilibili
C++代码
class Solution {
public:
int coNo(TreeNode* node){
if(node==nullptr)return 0;
return 1+coNo(node->left)+coNo(node->right);
}
int countNodes(TreeNode* root) {
int cnt=coNo(root);
return cnt;
}
};