二叉树理论
二叉树种类
- 满二叉树
- 完全二叉树(底层连续)
- 二叉搜索树(节点元素有一定顺序)
- 平衡二叉搜索树(左子树与右子树高度差绝对值小于)
存储方式
- 链式存储
- 线式存储
二叉树的遍历
- 深度优先遍历
- 前序遍历 中左右
- 中序遍历 左中右
- 后序遍历 左右中
- 广度优先遍历
- 层序遍历 迭代法
LeetCode 144 前序遍历
class Solution {
public:
vector<int> res;
void dfs(TreeNode* cur) {
if (cur == nullptr) return;
res.push_back(cur->val);
dfs(cur->left);
dfs(cur->right);
}
vector<int> preorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
};
LeetCode 145 后序遍历
class Solution {
public:
vector<int> res;
void dfs(TreeNode* cur) {
if (cur == nullptr) return;
dfs(cur->left);
dfs(cur->right);
res.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
};
LeetCode 94 中序遍历
class Solution {
public:
vector<int> res;
void dfs(TreeNode* cur) {
if (cur == nullptr) return;
dfs(cur->left);
res.push_back(cur->val);
dfs(cur->right);
}
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
};
LeetCode 102 层序遍历
class Solution {
public:
queue<TreeNode*> q;
vector<vector<int>> res;
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == nullptr) return {};
q.push(root);
while (!q.empty()) {
int size = q.size();
vector<int> path;
for (int i = 0; i < size; i ++) {
TreeNode* temp = q.front();
q.pop();
path.push_back(temp->val);
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
}
res.push_back(path);
}
return res;
}
};
二叉搜索树
- 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 它的左、右子树也分别为二叉搜索树
分类:
LeetCode刷题
, 二叉树
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律