大纲
● 104.二叉树的最大深度
● 559.n叉树的最大深度
● 111.二叉树的最小深度
● 222.完全二叉树的节点个数
二叉树的最大深度
题目链接:104.二叉树的最大深度
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数
叶子节点是左右孩子节点都为空的节点
分析过程:
可以递归法解决本题,递归的参数是节点、路径节点数量、最大节点深度值
递归结束条件是节点为空
递归单层循环是节点的左右子节点求深度。
void _maxDepth(TreeNode* root, int count, int & max) {if (!root) {if (max < count)max = count;return;}count++;_maxDepth(root->left, count, max);_maxDepth(root->right, count, max);count--;
}int maxDepth(TreeNode* root)
{int max = 0;_maxDepth(root, 0, max);return max;
}
n叉树的最大深度
本题解题思路和二叉树的最大深度是一样的,但是需要特别注意n叉数的最大深度递归的结束条件需要判断节点是否有孩子节点及节点为空的情况。
void maxNDepthFunc(Node* root, int count, int& max) {
// cout << "max:" << max << "," << count << endl;if (!root) {max = max < count ? count : max;return;}if (root->children.empty()) {max = max < count + 1 ? count + 1 : max;return;}count++;for (int i = 0; i < root->children.size(); ++i) {maxNDepthFunc(root->children[i], count, max);}count--;
}
int maxDepth(Node* root) {int max = 0;maxNDepthFunc(root, 0, max);return max;
}
二叉树的最小深度
题目链接:111.二叉树的最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数量
分析过程:
本题的解题思路和二叉树的最大深度还是有些不一样的,需要判断是否是叶子节点
void _minDepth(TreeNode* root, int count, int & min) {if (!root) {if (min > count)min = count;return;}if (!root->left && !root->right) {if (min > count)min = count;return;}count++;_minDepth(root->left, count, min);_minDepth(root->right, count, min);count--;
}int minDepth(TreeNode* root)
{int min = INT_MIN;_minDepth(root, 0, min);return min;
}
完全二叉树的节点个数
题目链接:222.完全二叉树的节点个数
分析过程:
本题的解题思路是使用后序遍历来统计节点个数
int countNodes(TreeNode* root) {if (root == NULL) return 0;return 1 + countNodes(root->left) + countNodes(root->right);
}