代码随想录算法训练营第11天|二叉树的遍历(递归与迭代)
递归遍历
前序遍历
class Solution {
public:
void Traversal(TreeNode* root, vector<int>& result)
{
if(root == nullptr)
return;
result.push_back(root -> val);
Traversal(root -> left, result);
Traversal(root -> right, result);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
Traversal(root, result);
return result;
}
};
中序遍历
class Solution {
public:
void Traversal(TreeNode* root, vector<int>& result)
{
if(root == nullptr)
return;
Traversal(root -> left, result);
result.push_back(root -> val);
Traversal(root -> right, result);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
Traversal(root, result);
return result;
}
};
后序遍历
class Solution {
public:
void Traversal(TreeNode* root, vector<int>& result)
{
if(root == nullptr)
return;
Traversal(root -> left, result);
Traversal(root -> right, result);
result.push_back(root -> val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
Traversal(root, result);
return result;
}
};
迭代遍历
前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if(root == nullptr)
return result;
stack<TreeNode*> st;
st.push(root);
while(!st.empty())
{
TreeNode* cur = st.top();
st.pop();
result.push_back(cur -> val);
if(cur -> right != nullptr)
st.push(cur -> right);
if(cur -> left != nullptr)
st.push(cur -> left);
}
return result;
}
};
中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
if(root == nullptr)
return result;
stack<TreeNode*> st;
//st.push(root);
TreeNode* cur = root;
while(cur != nullptr || !st.empty())
{
if(cur != nullptr)
{
st.push(cur);
cur = cur -> left;
}
else
{
cur = st.top();
st.pop();
result.push_back(cur -> val);
cur = cur -> right;
}
}
return result;
}
};
后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root == nullptr)
return result;
stack<TreeNode*> st;
st.push(root);
while(!st.empty())
{
TreeNode* cur = st.top();
st.pop();
result.push_back(cur -> val);
if(cur -> left != nullptr)
st.push(cur -> left);
if(cur -> right != nullptr)
st.push(cur -> right);
}
reverse(result.begin(), result.end());
return result;
}
};
总结
日期: 2023 年 3 月 28 日
学习时长: 1 h 0 m
难度:
★
\bigstar
★
累计完成题目数量: 35
距离目标还有数量: 265
小结:
- 递归法普遍好写,迭代法需要思考
- 递归的前序和后序只需要微小改变就可以
- 三种迭代都使用栈