Leetcode 104.二叉树的最大深度
链接:104.二叉树的最大深度
thought:
- 利用BFS(层序遍历)可解此题,可用队列,设置变量line_count,每层遍历完+1
- 利用DFS(本题采用后序遍历),可用递归或栈
- DFS: 此树的深度和其左(右)子树的深度之间的关系。显然,此树的深度 等于 左子树的深度 与 右子树的深度中的 最大值 +1+1+1 。
- 以后序为例,确定参数:根节点**;确定终止条件:节点为空;**单层递归逻辑:求左右子树高度,其中的max+1即为当前树的最大深度
完整C++代码如下:
//DFS
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root)
return 0;
int num1 = maxDepth(root->left);
int num2 = maxDepth(root->right);
int maxN = 1 + max(num1, num2);
return maxN;
};
};
//BFS
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> que;
int count=0;
if (root)
que.push(root);
while (!que.empty()) {
int size = que.size();
count++;
for (int i = 0; i < size; i++) {
TreeNode* cur = que.front();
que.pop();
vec.push_back(cur->val);
if (cur->left)
que.push(cur->left);
if (cur->right)
que.push(cur->right);
}
}
return count;
}
};
Leetcode 111. 二叉树的最小深度
thought:仍然是后序遍历,不过处理了!root->left && root->right
和root->left && !root->right
两种情况
完整C++代码如下:
//DFS
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root)
return 0;
else
return minD(root);
};
int minD(TreeNode* root) {
if (!root->left && !root->right)
return 1;
else if (!root->left && root->right) {
return 1 + minD(root->right);
} else if (root->left && !root->right) {
return 1 + minD(root->left);
} else {
return 1 + min(minD(root->left), minD(root->right));
}
}
};
Leetcode 222.完全二叉树的节点个数
thought:
-
本质是每轮确定一个节点,若其左右子树都为满二叉树,直接返回,反之则进行递归
-
原理如下:
-
如果根节点的左子树深度等于右子树深度,则说明 左子树为满二叉树
-
如果根节点的左子树深度大于右子树深度,则说明 右子树为满二叉树
原链接来自 :link 作者:左
完整C++代码如下:
class Solution {
public:
int countLevels(TreeNode* root) {
int level = 0;
while (root != nullptr) {
level++;
root = root->left;
}
return level;
}
int countNodes(TreeNode* root) {
int l_depth = countLevels(root);
return count(root, l_depth - 1);
}
int count(TreeNode* root, int l_depth) {
if (!root)
return 0;
int r_depth = countLevels(root->right);
if (l_depth == r_depth)
return (1 << l_depth) + count(root->right, r_depth - 1);
else
return (1 << r_depth) + count(root->left, l_depth - 1);
}
};