二叉树前中后序遍历递归法&迭代法
作者:互联网
1.1. 前序遍历--递归
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { // 递归 vector<int> ans; preTravel(root, ans); return ans; } void preTravel(TreeNode* root, vector<int>& ans){ if(root == nullptr) return; ans.push_back(root->val); // 根 preTravel(root->left, ans); // 左 preTravel(root->right, ans); // 右 } };1.2. 前序遍历--迭代
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { // 迭代 vector<int> ans; if(root == nullptr) return ans; stack<TreeNode*> st; st.push(root); while(!st.empty()){ TreeNode* cur = st.top(); st.pop(); ans.push_back(cur->val); // 根 if(cur->right != nullptr) st.push(cur->right); // 右 if(cur->left != nullptr) st.push(cur->left); // 左 栈:先进后出,最后遍历结果是 根->左->右 } return ans; } };
2.1. 中序遍历--递归
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; inTravel(root, ans); return ans; } void inTravel(TreeNode* root, vector<int>& ans){ if(root == nullptr) return; inTravel(root->left, ans); // 左 ans.push_back(root->val); // 根 inTravel(root->right, ans); // 右 } };2.2. 中序遍历--迭代
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; if(root == nullptr) return ans; stack<TreeNode*> st; TreeNode* cur = root; while(cur != nullptr || !st.empty()){ while(cur != nullptr){ st.push(cur); cur = cur->left; } cur = st.top(); st.pop(); ans.push_back(cur->val); cur = cur->right; } return ans; } };3.1. 后序遍历--递归
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> ans; postTravel(root, ans); return ans; } void postTravel(TreeNode* root, vector<int>& ans){ if(root == nullptr) return; postTravel(root->left, ans); // 左 postTravel(root->right, ans); // 右 ans.push_back(root->val); // 根 } };3.2. 后序遍历--迭代
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> ans; if(root == nullptr) return ans; stack<TreeNode*> st; st.push(root); while(!st.empty()){ TreeNode* cur = st.top(); st.pop(); ans.push_back(cur->val); // 根 if(cur->left != nullptr) st.push(cur->left); // 左 if(cur->right != nullptr) st.push(cur->right); // 右, 栈:先进后出,根->右->左 } reverse(ans.begin(), ans.end()); // 左->右->根 return ans; } };
标签:cur,前中,st,vector,二叉树,ans,push,迭代法,root 来源: https://www.cnblogs.com/tristatl/p/14825858.html