代码随想录打卡day14
二叉树1
1.二叉树理论基础
1.1 二叉树的分类:满二叉树、完全二叉树(最下层集中在左侧,为层序遍历服务)、二叉搜索树、平衡二叉搜索树(高度差<=1)
1.2 二叉树的存储:链式存储(指针,也是主要的存储方式)、顺序存储
1.3 二叉树的定义方式
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
2.二叉树的遍历
2.1 递归遍历(前序、中序、后序)
2.1.1 144二叉树的前序遍历
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& vec){
if(cur == NULL){
return;
}
vec.push_back(cur->val);//前序中左右
traversal(cur->left, vec);
traversal(cur->right, vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root,result);
return result;
}
};
2.1.2 145二叉树的后序遍历
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& vec){
if(cur == NULL){
return;
}
traversal(cur->left, vec);
traversal(cur->right, vec);
vec.push_back(cur->val);//后序左右中
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root, result);
return result;
}
};
2.1.3 94 二叉树的中序遍历
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& vec){
if(cur == NULL){
return;
}
traversal(cur->left, vec);
vec.push_back(cur->val);
traversal(cur->right, vec);//中序左中右
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root, result);
return result;
}
};
2.2 层次遍历(迭代遍历)
2.2.1前序
class Solution {//迭代
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* temp;
st.push(root);
if(root == NULL) return result;
while(!st.empty()){
temp = st.top();
result.push_back(temp->val);
st.pop();
if(temp->right) st.push(temp->right);//记得要判断一下节点是否为空
if(temp->left) st.push(temp->left);
}
return result;
}
};
2.2.2后序(相比前序就是改变一下顺序并反转)
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* temp;
st.push(root);
if(root == NULL) return result;
while(!st.empty()){
temp = st.top();
result.push_back(temp->val);
st.pop();
if(temp->left) st.push(temp->left);
if(temp->right) st.push(temp->right);//记得要判断一下节点是否为空
}
reverse(result.begin(),result.end());
return result;
}
};
2.2.3中序(这里要多想想while的条件)
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = root;
if(root == NULL) return result;
while(cur != NULL || !st.empty()){
if(cur != NULL){
st.push(cur);
cur = cur->left;
}
else{
cur = st.top();
result.push_back(cur->val);
st.pop();
cur = cur->right;
}
}
return result;
}
};