代码随想录算法训练营第十六天
一、104.二叉树的最大深度
-
递归法
- 二叉树节点的深度(前序遍历):指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度(后序遍历):指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)
- 根节点的高度就是二叉树的最大深度
前序遍历:
class Solution {
public:
void max_depth(TreeNode* root, int count, int& result){
if(root == NULL){
result = result>count ? result:count;
count--;
return ;
}
count++;
max_depth(root->left, count, result);
max_depth(root->right, count, result);
}
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
int result = 1;
int count = 0;
max_depth(root,count,result);
return result;
}
};
后序遍历:
class Solution {
public:
int getheight(TreeNode* Node){
if(Node == NULL) return 0;
int LeftHeight = getheight(Node->left);
int RightHeight = getheight(Node->right);
int Height = 1 + max(LeftHeight,RightHeight);
return Height;
}
int maxDepth(TreeNode* root) {
return getheight(root);
}
};
class Solution {
public:
int maxDepth(TreeNode* root) {
int result = 0;
if(root == NULL) return result;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
result++;
int size = que.size();
while(size--){
TreeNode* node = que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return result;
}
};
二、二叉树的最小深度
**求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。**需要左右孩子都不为空的时候,才比较选取最小值。
class Solution {
public:
int getdepth(TreeNode* cur){
if(cur == NULL) return 0;
int leftheight = getdepth(cur->left);
int rightheight = getdepth(cur->right);
if(cur->left == NULL && cur->right != NULL) return 1+rightheight;
else if(cur->left != NULL && cur->right == NULL) return 1+leftheight;
else
return 1+min(leftheight,rightheight);
}
int minDepth(TreeNode* root) {
return getdepth(root);
}
};
三、222.完全二叉树的节点个数
不考虑完全二叉树的情况下,按递归法遍历一次统计节点个数:
class Solution {
public:
int getcount(TreeNode* node){
if(node == NULL) return 0;
int leftnum = getcount(node->left);
int rightnum = getcount(node->right);
int total = 1 + leftnum + rightnum;
return total;
}
int countNodes(TreeNode* root) {
return getcount(root);
}
};
考虑完全二叉树的情况,满二叉树的节点个数为2^k,如果整个树不是满二叉树,就递归其左右孩子,直到遇到满二叉树为止,用公式计算这个子树(满二叉树)的节点数量。在完全二叉树中,如果递归向左遍历的深度等于递归向右遍历的深度,那说明就是满二叉树。
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
TreeNode* lefttree = root->left;
TreeNode* righttree = root->right;
int leftdepth = 0;
int rightdepth = 0;
while(lefttree){
leftdepth++;
lefttree = lefttree->left;
}
while(righttree){
rightdepth++;
righttree = righttree->right;
}
if(leftdepth == rightdepth){
return (2 << leftdepth) -1;
}
return countNodes(root->left) + countNodes(root->right) +1;
}
};