二叉树的递归遍历
力扣题目链接-前序遍历
力扣题目链接-后序遍历
力扣题目链接-中序遍历
题目描述
给你二叉树的根节点,分别前序/后序/中序遍历输出节点。
算法描述
关于迭代
迭代和递归很像,迭代是一次次升级的过程,需要我们使用已有的数据去计算出后面的数据,这里使用迭代法遍历二叉树比递归要麻烦一些,但是需要一层层调用方法,避免了递归中可能出现的栈溢出。
解题思路
这里其实前序和后续比较简单,主要是中序遍历比较麻烦。
题解
前序遍历
class Solution {
public:vector<int> preorderTraversal(TreeNode* root) {vector<int> ans;stack<TreeNode*> st;if(root == nullptr){return ans;}st.push(root);while(!st.empty()){TreeNode* cur = st.top();ans.push_back(cur->val);st.pop();if(cur->right){st.push(cur->right);}if(cur->left){st.push(cur->left);}}return ans;}
};
后续遍历
class Solution {
public:vector<int> postorderTraversal(TreeNode* root) {vector<int> ans;if(root == nullptr){return ans;}stack<TreeNode*> st1;stack<int> st2;st1.push(root);while(!st1.empty()){TreeNode* cur = st1.top();st2.push(cur->val);st1.pop();if(cur->left){st1.push(cur->left);}if(cur->right){st1.push(cur->right);}}while(!st2.empty()){ans.push_back(st2.top());st2.pop();}return ans;}
};
中序遍历
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {vector<int> ans;if(root == nullptr){return ans;}stack<TreeNode*> st;TreeNode* cur = root;while(!st.empty() || cur != nullptr){if(cur != nullptr){st.push(cur);cur = cur->left;}else{cur = st.top();st.pop();ans.push_back(cur->val);cur = cur->right;}}return ans;}
};