104. 二叉树的最大深度
题目链接:104. 二叉树的最大深度
文档讲解:代码随想录
视频讲解:二叉树的高度和深度有啥区别?究竟用什么遍历顺序?很多录友搞不懂 | LeetCode:104.二叉树的最大深度
思路
一般前序遍历用来求深度,后序遍历用来求高度,根节点的高度就是二叉树的最大深度,因此本题既可以用后序遍历也可以用前序遍历。
代码
后序遍历
class Solution {
public:
int maxDepth(TreeNode *root) {
return getdepth(root);
}
private:
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;
}
};
前序遍历
class Solution {
public:
int maxDepth(TreeNode *root) {
result = 0;
if (root == NULL)
return 0;
getdepth(root, 1);
return result;
}
private:
int result;
void getdepth(TreeNode *node, int depth) {
result = depth > result ? depth : result; // 中
if (node->left == NULL && node->right == NULL)
return;
if (node->left) { // 左
depth++; // 深度+1
getdepth(node->left, depth);
depth--; // 回溯,深度-1
}
if (node->right) { // 右
depth++; // 深度+1
getdepth(node->right, depth);
depth--; // 回溯,深度-1
}
}
};
相关题目
35.搜索插入位置
34. 在排序数组中查找元素的第一个和最后一个位置
69. x 的平方根
367. 有效的完全平方数
111. 二叉树的最小深度
题目链接:111. 二叉树的最小深度
文档讲解:代码随想录
思路
根节点的最小深度也就是根节点的最小高度,使用后序遍历。
代码
后序遍历
class Solution {
public:
int minDepth(TreeNode *root) {
return getdepth(root);
}
private:
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;
return 1 + min(leftDepth, rightDepth);
}
};
222. 完全二叉树的节点个数
题目链接:222. 完全二叉树的节点个数
文档讲解:代码随想录
视频讲解:要理解普通二叉树和完全二叉树的区别! | LeetCode:222.完全二叉树节点的数量
思路
可以当作普通二叉树使用层序遍历或者递归的方式求解,也可以使用完全二叉树的性质求解。
代码
普通二叉树层序遍历求解
class Solution {
public:
int countNodes(TreeNode *root) {
queue<TreeNode *> que;
int nodeNum = 0;
if (root)
que.push(root);
while (!que.empty()) {
int size = que.size();
while (size--) {
TreeNode *cur = que.front();
que.pop();
nodeNum++;
if (cur->left)
que.push(cur->left);
if (cur->right)
que.push(cur->right);
}
}
return nodeNum;
}
};
普通二叉树递归求解
class Solution {
public:
int countNodes(TreeNode *root) {
nodeNum = 0;
getNodeNum(root);
return nodeNum;
}
private:
int nodeNum;
void getNodeNum(TreeNode *node) {
if (node == NULL)
return;
nodeNum++;
getNodeNum(node->left);
getNodeNum(node->right);
}
};
完全二叉树性质求解
class Solution {
public:
int countNodes(TreeNode *root) {
return getCount(root);
}
private:
int getCount(TreeNode *node) {
if (node == NULL)
return 0;
int leftDepth = 1;
int rightDepth = 1;
TreeNode *leftNode = node->left;
TreeNode *rightNode = node->right;
while (leftNode) {
leftDepth++;
leftNode = leftNode->left;
}
while (rightNode) {
rightDepth++;
rightNode = rightNode->right;
}
if (leftDepth == rightDepth)
return pow(2, leftDepth) - 1;
int leftCount = getCount(node->left);
int rightCount = getCount(node->right);
return leftCount + rightCount + 1;
}
};