代码随想录算法训练营第十四天|144.二叉树的前序遍历、94.二叉树的中序遍历、145.二叉树的后序遍历
文章讲解《代码随想录》: https://programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%80%92%E5%BD%92%E9%81%8D%E5%8E%86.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
递归遍历代码来自y总:http://www.acwing.com
144.二叉树的前序遍历
迭代遍历,先看代码:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
vector<int> res;
if(root == NULL) return res;
stk.push(root);
while(!stk.empty())
{
TreeNode* cur = stk.top();
res.push_back(cur->val);
stk.pop();
//if(cur->left) stk.push(cur->left);
if(cur->right) stk.push(cur->right);
if(cur->left) stk.push(cur->left);
}
return res;
}
};
递归遍历:
class Solution {
public:
vector<int> ans;
vector<int> preorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root) {
if(!root) return;
ans.push_back(root->val);
dfs(root->left);
dfs(root->right);
}
};
递归遍历,其实不止递归遍历,只要涉及数的算法,都要注意一条,就是一定要判断root是否为空,其他的没有什么了。
然后是迭代遍历,前序遍历很有意思,用一个栈来辅助,保持着中左右的原则,先让中进栈,然后中出栈,然后右进栈,再左进栈,因为出栈顺序就是左先出栈,然后右出栈,这样达到中左右。
94.二叉树的中序遍历
递归遍历:
class Solution {
public:
vector<int> ans;
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root) {
if(!root) return;
dfs(root->left);
ans.push_back(root->val);
dfs(root->right);
}
};
迭代遍历:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
if(root == NULL) return res;
TreeNode* cur = root;
while(cur || !stk.empty())
{
if(cur != NULL)
{
stk.push(cur);
cur = cur->left;
}
else
{
cur = stk.top();
res.push_back(cur->val);
stk.pop();
cur = cur->right;
}
}
return res;
}
};
递归遍历还是,注意判断root。
迭代遍历和前序的迭代不太一样,这次是左中右,其实左的话,可以看作它既是左,又是中,所以碰到左子树就进栈,直到为空就出栈,有的节点出栈是作为本层的父节点,同时又代表上一层的左节点,然后将指针指向右节点,只要右节点还有左子树,那会继续往左走,要是没有子树就输出右节点。
145.二叉树的后序遍历
递归遍历:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
if(root == NULL) return res;
stk.push(root);
while(!stk.empty())
{
TreeNode* cur = stk.top();
stk.pop();
res.push_back(cur->val);
if(cur->left) stk.push(cur->left);
if(cur->right) stk.push(cur->right);
}
reverse(res.begin(),res.end());
return res;
}
};
递归遍历还是注意root,迭代遍历很巧妙,可以看看《代码随想录》的题解,思想和前序的迭代一样,但是是:中右左,的排列,最后再整体翻转,成为左右中排列。
后面面有个统一迭代,我目前没太多时间看,有时间更一下。