题1:
指路:LeetCode104 二叉树的最大深度
思路与代码:
1.递归
求左右子树的最大深度后加1(根到子树也有1个深度单位)。代码如下:
class Solution {
public:
int maxDepth(TreeNode* root) {
int ans = 0;
if (root == NULL) return 0;
int leftdepth = maxDepth(root->left);
int rightdepth = maxDepth(root->right);
ans = max(leftdepth, rightdepth) + 1;
return ans;
}
};
2.迭代(层序遍历)
见二叉树的层序遍历。代码如下:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
int depth = 0;
queue<TreeNode*> que; // 队列用来放节点
que.push(root);
while (!que.empty()) {
int size = que.size();
depth++; // 向下一层深度加1
while (size--) {
TreeNode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return depth;
}
};
题2:
指路:LeetCode111 二叉树的最小深度
思路与代码:
最小深度应注意当左子树和右子树都为空时的限制条件。代码如下:
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> que;
if (root == NULL) return 0;
que.push(root);
int depth = 0;
//vector<int> vec;
while (!que.empty()) {
int size = que.size();
// vec.push_back(size);
depth++;
while (size--) {
TreeNode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
if (!node->left && !node->right) {
return depth;
}
}
}
return depth;
}
};
题3:
指路:LeetCode222 完全二叉树的节点个数
思路与代码:
差异不大,统计一下size就行。代码如下:
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
if(root == NULL) return 0;
que.push(root);
int ans = 0;
while (!que.empty()) {
int size = que.size();
ans += size;
while (size--) {
TreeNode* node = que.front();
que.pop();
// ans++;
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return ans;
}
};