LeetCode104 二叉树的最大深度
题目链接:二叉树的最大深度
思路
本题采用后序递归遍历可得到根节点的高度,即为二叉树的最大深度,比较好写。真正求深度的逻辑则是采用前序遍历(回溯),补充:
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
还可以采用层次遍历(迭代法)求出二叉树层数以得到最大深度,详情均可见代码随想录
代码
class Solution {
public:
int getdepth(TreeNode* node) {
if (node == NULL)
return 0;
int leftdepth = getdepth(node->left); // 左
int rightdepth = getdepth(node->right); // 右
int depth = 1 + max(leftdepth, rightdepth); // 中
return depth;
}
int maxDepth(TreeNode* root) { return getdepth(root); }
};
复杂度
时间复杂度:O(n)
空间复杂度:O(height) height为二叉树高度
LeetCode559 n叉树的最大深度
题目链接:n叉树的最大深度
思路
同上题,直接附代码
代码
class Solution {
public:
int maxDepth(Node* root) {
if (root == nullptr)
return 0;
int depth = 0;
for (int i = 0; i < root->children.size(); i++) {
depth = max(depth, maxDepth(root->children[i]));
}
return depth + 1;
}
};
复杂度
时间复杂度:O(n)
空间复杂度:O(height)
Leetcode111 二叉树的最小深度
题目链接:二叉树的最小深度
思路
求二叉树最小深度看似与求最大深度类似,实则处理起来还是更麻烦一些:最小深度概念为从根节点到最近叶子节点的最短路径上的节点数量,下图中的例子便需要特殊讨论①若左子树为空,右子树不为空,则最小深度为1+右子树最小深度;②若右子树为空,左子树不为空,则最小深度为1+左子树最小深度;③若左右子树都不为空,则最小深度为1+min(左子树最小深度,右子树最小深度)。
代码
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == NULL)
return 0;
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
// 中
// 当一个左子树为空,右不为空
if (node->left == NULL && node->right != NULL) {
return 1 + rightDepth;
}
// 当一个右子树为空,左不为空
if (node->left != NULL && node->right == NULL) {
return 1 + leftDepth;
}
int result = 1 + min(leftDepth, rightDepth);
return result;
}
int minDepth(TreeNode* root) { return getDepth(root); }
};
复杂度
时间复杂度:O(n)
空间复杂度:O(height)
Leetcode222 完全二叉树的节点个数
题目链接:完全二叉树的节点个数
思路
与求深度类似,采用后序遍历,将max换成求和,递归后即可得完全二叉树的节点个数。
代码
class Solution {
private:
int getNodesNum(TreeNode* cur) {
if (cur == NULL) return 0;
int leftNum = getNodesNum(cur->left); // 左
int rightNum = getNodesNum(cur->right); // 右
int treeNum = leftNum + rightNum + 1; // 中
return treeNum;
}
public:
int countNodes(TreeNode* root) {
return getNodesNum(root);
}
};
复杂度
时间复杂度:O(n)
空间复杂度:O(height)