解题思路:
- 迭代法:函数外声明一个全局变量或 class 内置变量用于记录最大深度
- 递归法:
// 递归法
class Solution {
public:
void order(TreeNode* cur, int cur_depth) {
if (cur == nullptr) return;
cur_depth += 1;
if (cur_depth > max_depth_) max_depth_ = cur_depth;
order(cur->left, cur_depth);
order(cur->right, cur_depth);
}
int maxDepth(TreeNode* root) {
order(root, 0);
return max_depth_;
}
private:
int max_depth_ = 0;
};
// 迭代法(自己写的)
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
queue<TreeNode*> node_q;
node_q.push(root);
int max_depth = 0;
while (!node_q.empty()) {
int size = node_q.size();
for (int i = 0; i < size; i++) {
TreeNode* tmp_node = node_q.front();
node_q.pop();
if (tmp_node->left) node_q.push(tmp_node->left);
if (tmp_node->right) node_q.push(tmp_node->right);
}
max_depth++;
}
return max_depth;
}
// 递归法(最优)
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
解题思路:最小深度是从根节点到最近 “叶子节点” 的最短路径上的节点数量
// 迭代,层序遍历找到第一个叶子结点,此时就是最小深度
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
int min_depth = 1;
queue<TreeNode*> node_q;
node_q.push(root);
while (!node_q.empty()) {
int size = node_q.size();
for (int i = 0; i < size; i++) {
TreeNode* tmp_node = node_q.front();
node_q.pop();
if (!tmp_node->left && !tmp_node->right) return min_depth;
if (tmp_node->left) node_q.push(tmp_node->left);
if (tmp_node->right) node_q.push(tmp_node->right);
}
min_depth++;
}
return min_depth;
}
// 递归法
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
if (root->left && !root->right) {
return 1 + minDepth(root->left);
} else if (!root->left && root->right) {
return 1 + minDepth(root->right);
}
return 1 + min(minDepth(root->left), minDepth(root->right));
}
解题思路:题目中给出的树全部都是完全二叉树,要么满树,要么叶子节点不齐
int countNodes(TreeNode* root) {
if (root == nullptr) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int left_depth = 0, right_depth = 0;
while(left) {
left = left->left;
left_depth++;
}
while(right) {
right = right->right;
right_depth++;
}
if (left_depth == right_depth) {
return (2 << left_depth) - 1;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}