二叉树的4种遍历方式(前、中、后序–递归和迭代法)(层序-迭代法)
前序遍历
递归
void traversal(TreeNode* curr, vector<int> &vec)
{
if(curr==nullptr)
{
return;
}
vec.push_back(curr->val);
traversal(curr->left,vec);
traversal(curr->right,vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> vec;
traversal(root,vec);
return vec;
}
迭代
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
if(root!=nullptr)
{
st.push(root);
}
while(!st.empty())
{
TreeNode* node=st.top();
st.pop();
result.push_back(node->val);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
return result;
}
中序遍历
递归
void traversal(TreeNode* curr,vector<int> &vec)
{
if(curr==nullptr) return;
traversal(curr->left,vec);
vec.push_back(curr->val);
traversal(curr->right,vec);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> vec;
traversal(root,vec);
return vec;
}
迭代
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
TreeNode* curr=root;
while(curr!=nullptr || !st.empty())
{
if(curr!=nullptr)
{
st.push(curr);
curr=curr->left;
}
else
{
curr=st.top();
st.pop();
result.push_back(curr->val);
curr=curr->right;
}
}
return result;
}
后序遍历
递归
void traversal(TreeNode* curr, vector<int>& vec)
{
if(curr==nullptr) return;
traversal(curr->left,vec);
traversal(curr->right,vec);
vec.push_back(curr->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root,result);
return result;
}
迭代
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if(root!=nullptr) st.push(root);
while(!st.empty())
{
TreeNode* node=st.top();
st.pop();
result.push_back(node->val);
if(node->left) st.push(node->left);
if(node->right) st.push(node->right);
}
reverse(result.begin(),result.end());
return result;
}
层序遍历
迭代
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
queue<TreeNode*> que;
if(root!=nullptr)
{
que.push(root);
}
while(!que.empty())
{
int size=que.size();
vector<int> vec;
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;
}
总结
递归法
前中后序的代码通用,层序无递归法
迭代法
前后序的代码通用,中序不太一样,层序类似前后序