144. 二叉树的前序遍历 - 力扣(LeetCode)
94. 二叉树的中序遍历 - 力扣(LeetCode)
145. 二叉树的后序遍历 - 力扣(LeetCode)
递归遍历
class Solution {
public:
vector<int>ans;
void fun(TreeNode* root){
if(root==nullptr){
return;
}
ans.push_back(root->val);
fun(root->left);
fun(root->right);
}
vector<int> preorderTraversal(TreeNode* root) {
fun(root);
return ans;
}
};
class Solution {
public:
vector<int>ans;
void fun(TreeNode* root){
if(root==nullptr){
return;
}
fun(root->left);
ans.push_back(root->val);
fun(root->right);
}
vector<int> inorderTraversal(TreeNode* root) {
fun(root);
return ans;
}
};
class Solution {
public:
vector<int>ans;
void fun(TreeNode* root){
if(root==nullptr){
return;
}
fun(root->left);
fun(root->right);
ans.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
fun(root);
return ans;
}
};
迭代遍历
思路:使用栈模拟递归
重点:中序遍历比较特殊,仔细看一下
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int>ans;
if(root==nullptr){
return ans;
}
st.push(root);
while(!st.empty()){
TreeNode* tmp=st.top();//中
st.pop();
ans.push_back(tmp->val);
if(tmp->right){//右 空结点不入栈
st.push(tmp->right);
}
if(tmp->left){//左
st.push(tmp->left);
}
}
return ans;
}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur != NULL || !st.empty()) {
if (cur != NULL) { // 指针来访问节点,访问到最底层
st.push(cur); // 将访问的节点放进栈
cur = cur->left; // 左
} else {
cur = st.top(); // 从栈里弹出的数据,就是要处理的数据(放进result数组里的数据)
st.pop();
result.push_back(cur->val); // 中
cur = cur->right; // 右
}
}
return result;
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int>ans;
if(root==nullptr){
return ans;
}
st.push(root);
while(!st.empty()){
TreeNode* tmp=st.top();//中
st.pop();
ans.push_back(tmp->val);
if(tmp->left){//左
st.push(tmp->left);
}
if(tmp->right){//右 空结点不入栈
st.push(tmp->right);
}
}
reverse(ans.begin(),ans.end());
return ans;
}
};
层序遍历
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
vector<vector<int>> result;
while (!que.empty()) {
int size = que.size();
vector<int> vec;
// 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
vec.push_back(node->val);
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
result.push_back(vec);
}
return result;
}
};
总结
二叉树的遍历需要弄清楚,迭代遍历需要栈来模拟,层序遍历需要队列来模拟