1)递归 (深度优先搜索)
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftMax = maxDepth(root->left);
int rightMax = maxDepth(root->right);
return max(leftMax, rightMax) + 1;
}
};
2)迭代(广度优先搜索)
class Solution {
public:
int maxDepth(TreeNode* root) {
int ans = 0;
if (!root) {
return ans;
}
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
while (size--) {
root = que.front();
que.pop();
if (root->left) {
que.push(root->left);
}
if (root->right) {
que.push(root->right);
}
}
ans++;
}
return ans;
}
};
1.递归(深度优先搜索)
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) {
return 0;
}
if (!root->left && !root->right) {
return 1;
}
int dep_min = INT_MAX;
if (root->left) {
dep_min = min(minDepth(root->left), dep_min);
}
if (root->right) {
dep_min = min(minDepth(root->right), dep_min);
}
return dep_min + 1;
}
};
2.迭代(广度优先搜索)
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) {
return 0;
}
int ans = 1;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()){
int size = que.size();
while (size--) {
root = que.front();
que.pop();
if (!root->left && !root->right) {
return ans;
}
if (root->left) {
que.push(root->left);
}
if (root->right){
que.push(root->right);
}
}
ans++;
}
return ans;
}
};
1)遍历所有节点
class Solution {
public:
int countNodes(TreeNode* root) {
return root == nullptr ? 0 : countNodes(root->left) + countNodes(root->right) + 1;
}
};
2)判断中间是否有满二叉树,非遍历所有节点
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) {
return 0;
}
TreeNode* leftNode = root->left;
TreeNode* rightNode = root->right;
int leftDepth = 0, rightDepth = 0;
while (leftNode){
leftDepth++;
leftNode = leftNode->left;
}
while (rightNode) {
rightDepth++;
rightNode = rightNode->right;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};