1.二叉搜索树
2.平衡二叉搜索树
3.二叉树的存储方式
链式存储方式就用指针, 顺序存储的方式就是用数组。一般用链式。
4.二叉树的遍历方式
- 深度 (递归 / 迭代(栈))
- 递归-前序
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
traversal(root, res);
return res;
}
void traversal(TreeNode *cur, vector<int>& res){
if(cur == nullptr) return ;
res.push_back(cur->val);
traversal(cur->left, res);
traversal(cur->right, res);
}
};
递归-中序
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
//2
vector<int> res;
traversal(root, res);
return res;
}
void traversal(TreeNode* cur, vector<int>& res){
if(cur == nullptr) return ;
traversal(cur->left, res);
res.push_back(cur->val);
traversal(cur->right, res);
}
};
递归-后序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* temp = st.top();
st.pop();
if(temp->right != nullptr) st.push(temp->right);
if(temp->left != nullptr) st.push(temp->left);
res.push_back(temp->val);
}
return res;
}
};
- 迭代(栈)-前序
栈-处理顺序和访问顺序一致
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root == nullptr) return res;
st.push(root);
while(!st.empty()){
TreeNode* temp = st.top();
res.push_back(temp->val);
st.pop();
if(temp->right != nullptr) st.push(temp->right);//注意先放右再左
if(temp->left != nullptr) st.push(temp->left);
}
return res;
}
};
迭代(栈)-中序
栈-处理顺序和访问顺序不一致
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
TreeNode* cur = root;
while(cur != nullptr || !st.empty()){
if(cur == nullptr){//处理
cur = st.top();
res.push_back(cur->val);
st.pop();
cur = cur->right;
}else{//访问
st.push(cur);
cur = cur->left;
}
}
return res;
}
};
迭代(栈)-后序
栈-左右中,先序是中左右,做完先序反转res即可。
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root == nullptr) return res;
st.push(root);
while(!st.empty()){
TreeNode* temp = st.top();
st.pop();
res.push_back(temp->val);
if(temp->left != nullptr) st.push(temp->left);//不更改顺序
if(temp->right != nullptr) st.push(temp->right);
}
reverse(res.begin(), res.end());
return res;
}
};
-
广度 (迭代 / 队列)
队列
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
vector<vector<int>> res;
if(root == nullptr) return res;
q.push(root);
while(!q.empty()){
int n = q.size();
vector<int> v;
while(n--){
TreeNode* temp = q.front();
v.push_back(temp->val);
if(temp->left != nullptr) q.push(temp->left);
if(temp->right != nullptr) q.push(temp->right);
q.pop();
}
res.push_back(v);
}
return res;
}
};