二叉树的递归遍历
二叉树的前中后遍历其实就是中间节点的遍历顺序。
递归三要素:
- 确定递归函数的参数与返回值
//无需返回值
//需要知道当前节点,以及一个用于保存遍历结果的vector数组
void traversal(TreeNode* cur, vector<int>& vec)
- 确定终止条件
if (cur == NULL) return;
- 确定单层递归的处理逻辑
//以前序遍历为例
vec.push_back(cur->val); // 中
traversal(cur->left, vec); // 左
traversal(cur->right, vec); // 右
前序遍历
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& res){
if(cur == nullptr) return;
res.push_back(cur->val);
traversal(cur->left, res);
traversal(cur->right, res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
traversal(root, res);
return res;
}
};
中序遍历
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& res){
if(cur == nullptr) return;
traversal(cur->left, res);
res.push_back(cur->val);
traversal(cur->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
traversal(root, res);
return res;
}
};
后序遍历
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& res){
if(cur == nullptr) return;
traversal(cur->left, res);
traversal(cur->right, res);
res.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
traversal(root, res);
return res;
}
};
二叉树的迭代遍历 用栈模拟+使用空指针来统一风格
前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root!=nullptr) st.push(root);
while(!st.empty()){
TreeNode* cur = st.top();
st.pop();
if(cur != nullptr){
if(cur->right!=nullptr) st.push(cur->right); // 右
if(cur->left!=nullptr) st.push(cur->left); // 左
st.push(cur); // 中
st.push(nullptr); //空节点表明轮到中节点
}
else{
cur = st.top();
st.pop();
res.push_back(cur->val);
}
}
return res;
}
};
中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
//迭代
stack<TreeNode*> st;
vector<int> res;
if(root!=nullptr) st.push(root);
while(!st.empty()){//栈非空
//中序遍历 左中右
TreeNode* cur = st.top();
st.pop();
if(cur!=nullptr){
if(cur->right!=nullptr) st.push(cur->right);
st.push(cur);
st.push(nullptr);
if(cur->left!=nullptr) st.push(cur->left);
}
else{//下一个节点为中节点
cur = st.top();
st.pop();
res.push_back(cur->val);
}
}
return res;
}
};
后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if(root!=nullptr) st.push(root);
while(!st.empty()){
TreeNode* cur = st.top();
st.pop();
if(cur != nullptr){
st.push(cur);
st.push(nullptr);
if(cur->right!=nullptr) st.push(cur->right);
if(cur->left!=nullptr) st.push(cur->left);
}
else{
cur = st.top();
st.pop();
res.push_back(cur->val);
}
}
return res;
}
};