算法记录Day 16 | 二叉树part03
LeetCode 104.二叉树的最大深度
题目链接:leetcode.cn/problems/ma…
题解
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
return max104(maxDepth(root->left), maxDepth(root->right)) + 1;
}
int max104(int a, int b) {
if (a > b) {
return a;
}
return b;
}
};
LeetCode 111.二叉树的最小深度
题目链接:leetcode.cn/problems/mi…
题解
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
if (root->left == nullptr && root->right == nullptr) {
return 1;
}
int left = minDepth(root->left);
int right = minDepth(root->right);
if (root->left == nullptr || root->right == nullptr) {
return left + right + 1;
}
return min111(left, right) + 1;
}
int min111(int a, int b) {
if (a < b) {
return a;
}
return b;
}
};
LeetCode 222.完全二叉树的节点个数
题目链接:leetcode.cn/problems/co…
题解
class Solution {
public:
int count = 0;
int countNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
helper(root);
return count;
}
void helper(TreeNode* node) {
if (node == nullptr) {
return;
}
count++;
helper(node->left);
helper(node->right);
return;
}
};