文档讲解:代码随想录 (programmercarl.com)
视频讲解:代码随想录的个人空间-代码随想录个人主页-哔哩哔哩视频 (bilibili.com)
LeetCode 递归遍历
题目链接:144. 二叉树的前序遍历 - 力扣(LeetCode)145. 二叉树的后序遍历 - 力扣(LeetCode)94. 二叉树的中序遍历 - 力扣(LeetCode)
代码如下:
class Solution {
public:
void preorder(TreeNode* root,vector<int> &res){
if(!root)return;
res.push_back(root->val);
preorder(root->left,res);
preorder(root->right,res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int>res;
preorder(root,res);
return res;
}
};
class Solution {
public:
void postorder(TreeNode* root,vector<int>& res){
if(!root)return;
postorder(root->left,res);
postorder(root->right,res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int>res;
postorder(root,res);
return res;
}
};
class Solution {
public:
void inorder(TreeNode* root,vector<int>& res){
if(!root)return;
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root,res);
return res;
}
};
LeetCode 迭代遍历
题目链接:144. 二叉树的前序遍历 - 力扣(LeetCode)
解题思路:前序遍历:利用栈,中右左的顺序保存。后序遍历:参考前序,翻转即可。中序:需要借用指针的遍历来帮助访问节点,栈则用来处理节点上的元素。
解题代码如下:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int>res;
if(!root)return res;
st.push(root);
while(!st.empty()){
TreeNode* node=st.top();
res.push_back(node->val);
st.pop();
if(node->right)st.push(node->right);
if(node->left)st.push(node->left);
}
return res;
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*>st;
vector<int>res;
if(!root)return res;
st.push(root);
while(!st.empty()){
TreeNode* node=st.top();
st.pop();
res.push_back(node->val);
if(node->left)st.push(node->left);
if(node->right)st.push(node->right);
}
reverse(res.begin(),res.end());
return res;
}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> res;
TreeNode* cur=root;
while(!st.empty()||cur){
if(cur){
st.push(cur);
cur=cur->left;
}else{
cur=st.top();
st.pop();
res.push_back(cur->val);
cur=cur->right;
}
}
return res;
}
};
LeetCode 统一迭代
题目链接:94. 二叉树的中序遍历 - 力扣(LeetCode)
解题思路:加入空指针进行标记。
解题代码如下:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*>st;
if(root)st.push(root);
while(!st.empty()){
TreeNode* node=st.top();
if(node){
st.pop();
if(node->right)st.push(node->right);
st.push(node);
st.push(nullptr);
if(node->left)st.push(node->left);
}else{
st.pop();
res.push_back(st.top()->val);
st.pop();
}
}
return res;
}
};