二叉树的迭代遍历
前序:
//前序1 vector<int> preorderTraversal(TreeNode* root) { if(!root) return {}; vector<int> ans; vector<TreeNode*> stack; TreeNode* cur; stack.push_back(root); //前序为中左右,先压入右子树 while(!stack.empty()){ cur=stack.back(); stack.pop_back(); ans.push_back(cur->val); if(cur->right){ stack.push_back(cur->right); } if(cur->left){ stack.push_back(cur->left); } } return ans; }
//前序2(中序改的) vector<int> preorderTraversal(TreeNode* root) { vector<int> ans; vector<TreeNode*> stack; TreeNode* cur=root; while(cur||!stack.empty()){ while(cur){ ans.push_back(cur->val); stack.push_back(cur); cur=cur->left; } cur=stack.back(); stack.pop_back(); cur=cur->right; } return ans; }
中序
//中序 vector<int> preorderTraversal(TreeNode* root) { vector<int> ans; vector<TreeNode*> stack; TreeNode* cur=root; while(cur||!stack.empty()){ while(cur){ stack.push_back(cur); cur=cur->left; } cur=stack.back(); stack.pop_back(); ans.push_back(cur->val); cur=cur->right; } return ans; }
后序
//后序(左右中),将前序遍历(中左右)的左右反转,压入栈中输出 //后序(前序1改的) vector<int> preorderTraversal(TreeNode* root) { if(!root) return {}; vector<int> ans; vector<TreeNode*> stack; vector<int> houxu; TreeNode* cur; stack.push_back(root); //后序为左右中,先压入左子树 while(!stack.empty()){ cur=stack.back(); stack.pop_back(); houxu.push_back(cur->val); if(cur->left){ stack.push_back(cur->left); } if(cur->right){ stack.push_back(cur->right); } } for(int i=houxu.size()-1;i>=0;i--){ ans.push_back(houxu[i]); } return ans; }