1、二叉树最大深度
后序遍历——递归
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int leftdeep = maxDepth(root->left);
int rightdeep = maxDepth(root->right);
return 1 + max(leftdeep, rightdeep);
}
};
简化版
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
迭代法——层序遍历
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> que;
int deep = 0;
if (!root) return 0;
que.push(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode *temp = que.front();
que.pop();
if (temp->left) que.push(temp->left);
if (temp->right) que.push(temp->right);
}
deep++;
}
return deep;
}
};
2、N叉树的最大深度
class Solution {
public:
int maxDepth(Node* root) {
if (!root) return 0;
int depth = 0;
for (int i = 0; i < root->children.size(); i++) {
depth = max(depth, maxDepth(root->children[i]));
}
return depth + 1;
}
};
3、二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
int leftdepth = minDepth(root->left);
int rightdepth = minDepth(root->right);
if (!root->left && root->right) return rightdepth + 1;
if (root->left && !root->right) return leftdepth + 1;
return 1 + min(leftdepth, rightdepth);
}
};
4、完全二叉树的结点个数
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) return 0;
int num = 0;
return countNodes(root->left) + countNodes(root->right) + 1;
}
};