104.二叉树的最大深度
初见想法:直接往下遍历,然后深度+1,维护一个最大深度
class Solution {
public:
int maxDepth(TreeNode* root) {
return getDepth(root);
}
int getDepth(TreeNode* node)
{
if (node == nullptr) return 0;
int leftdepth = getDepth(node->left);
int rightdepth = getDepth(node->right);
return max(leftdepth, rightdepth) + 1;
}
};
使用递归的方法,先遍历至最底层,然后深度不断往上+1
111.二叉树的最小深度
初见想法:使用层序遍历,遍历至某一node,其左右子树皆为空, 需要维护一个depth
层序迭代法:
class Solution {
public:
int minDepth(TreeNode* root) {
int Depth = 0;
if (root == nullptr) return Depth;
queue<TreeNode*> que;
que.push(root);
while (!que.empty())
{
Depth++;
int sz = que.size();
for (int i = 0; i <sz; i++)
{
TreeNode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
if (node->left == nullptr && node->right == nullptr) return Depth;
}
}
return Depth;
}
};
递归法:
class Solution {
public:
int minDepth(TreeNode* root)
{
return getdepth(root);
}
int getdepth(TreeNode* node)
{
if (node == nullptr) return 0;
int leftdepth = getdepth(node->left);
int rightdepth = getdepth(node->right);
if (node->left == nullptr && node->right != nullptr) return 1 + rightdepth;
if (node->left != nullptr && node->right == nullptr) return 1 + leftdepth;
return 1 + min(leftdepth, rightdepth);
}
};
222.完全二叉树的节点个数
初见想法:看到这一题,啪就搞起来,很快啊,一个cnt, 一个递归遍历
class Solution {
public:
int cnt = 0;
int countNodes(TreeNode* root) {
traversal(root);
return cnt;
}
void traversal(TreeNode* node)
{
if (node == nullptr) return;
cnt++;
traversal(node->left);
traversal(node->right);
}
};