二叉树理论知识
文章链接 https://programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html
代码随想录算法训练营第十二天|Leetcode 144.二叉树的前序遍历,145.二叉树的后序遍历,94.二叉树的中序遍历
题目链接 144. 二叉树的前序遍历,145. 二叉树的后序遍历,94. 二叉树的中序遍历
文章链接 https://programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%80%92%E5%BD%92%E9%81%8D%E5%8E%86.html
视频链接 https://www.bilibili.com/video/BV1Wh411S7xt
递归
- 前序遍历
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;
}
};
- 后序遍历
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;
}
};
- 中序遍历
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;
}
};
迭代
- 前序遍历
思路:前序遍历是中左右,每次先处理的是中间节点,那么先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子。
要先加入 右孩子,因为这样出栈的时候才是中左右的顺序。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = nullptr;
st.push(root);
while(!st.empty()){
cur = st.top();
st.pop();
if(cur==NULL) continue;
result.push_back(cur->val);
st.push(cur->right);
st.push(cur->left);
}
return result;
}
};
- 后序遍历
思路:前序遍历是中左右,后序遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序,然后在反转result数组,输出的结果顺序就是左右中了
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = nullptr;
if(root==NULL) return result;
st.push(root);
while(!st.empty()){
cur = st.top();
st.pop();
if(cur==NULL) continue;
result.push_back(cur->val);
st.push(cur->left);
st.push(cur->right);
}
reverse(result.begin(),result.end());
return result;
}
};
- 中序遍历
思路:中序遍历是左中右,先访问的是二叉树顶部的节点,然后一层一层向下访问,直到到达树左面的最底部,再开始处理节点
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = root;
if(root==NULL) return result;
while(!st.empty()||cur!=NULL){
//左子树一层一层向下访问
if(cur!=NULL){
st.push(cur);
cur = cur->left;
}else{
cur = st.top();
st.pop();
result.push_back(cur->val);
//如果有节点为空,返回上一层
cur = cur->right;
}
}
return result;
}
};