代码随想录第16天| 二叉树3
104. 二叉树的最大深度(简单)
题目链接:104. 二叉树的最大深度
代码随想录:104. 二叉树的最大深度
1.迭代法:层序遍历
2.递归法 (后序遍历)
public:
int maxDepth(TreeNode* root) {
if(root == nullptr) return 0;
int left = maxDepth(root -> left);
int right = maxDepth(root -> right);
return 1 + max(maxDepth(root -> left), maxDepth(root -> right));
}
};
111. 二叉树的最小深度(简单)
LeetCode题目:111. 二叉树的最小深度
代码随想录:111. 二叉树的最小深度
1.第一反应思路:迭代法层序遍历
class Solution {
public:
int minDepth(TreeNode* root) {
int depth = 0;
queue<TreeNode *> que;
if(root) que.push(root);
while(!que.empty()){
int size = que.size();
depth++;
for(int i = 0; i < size; i++){
TreeNode * cur = que.front();
que.pop();
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
if(!cur->left && !cur->right)
return depth;
}
}
return depth;
}
};
递归有点难想
自己写的
int minDepth(TreeNode* root) {
if(!root) return 0;
//右空左不空,最小深度往左边找
if(root->left && !root->right)
return 1 + minDepth(root->left);
//左空右不空,最小深度往右找
if(!root->left && root->right)
return 1 + minDepth(root->right);
return 1 + min(minDepth(root->left), minDepth(root->right));
}
222. 完全二叉树的节点个数(中)
LeetCode题目:222. 完全二叉树的节点个数
代码随想录:222. 完全二叉树的节点个数
完全二叉树节点数n = 2h -1
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
int leftD = 0, rightD = 0;
TreeNode * left = root->left;
TreeNode * right = root->right;
while(left){
leftD++;
left = left->left;
}
while(right){
rightD++;
right = right->right;
}
// 完全二叉树
if(leftD == rightD)
return (2<<leftD) - 1;
else
return 1 + countNodes(root->left) +countNodes(root->right);
}
};