二叉树的前中后序遍历,可以用递归和迭代两种方法。
递归比较无脑,直接暴力就可以写出来;迭代需要手动维护一个栈,模拟递归调用,比较麻烦。
在这里给出我自己的递归解法,以及分享一个使用递归的思想实现迭代的解法。对二叉树递归解法不熟悉的朋友,可以参考我之前的一篇博客, LeetCode算法题解——二叉树的递归求解。
前序遍历
递归解法
这里也是很直接的递归思路:一般结点先访问根结点,再依次访问左、右结点;空结点返回空vector,然后再将思路反过来实现代码。
class Solution {
public:
vector<int> res;
vector<int> preorderTraversal(TreeNode* root)
{
if(root == NULL) return vector<int>();
res.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
return res;
}
};
迭代
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> call;
if(root != NULL) call.push(root);
while(!call.empty())
{
TreeNode *cur = call.top();
call.pop();
if(cur != NULL)
{
if(cur->right) call.push(cur->right);
if(cur->left) call.push(cur->left);
call.push(cur);
call.push(NULL);
}
else
{
res.push_back(call.top()->val);
call.pop();
}
}
return res;
}
};
中序遍历
递归解法
这里也是很直接的递归思路:一般结点先访问左结点,再依次访问根、右结点;空结点返回空vector,然后再将思路反过来实现代码。
class Solution {
public:
vector<int> res;
vector<int> inorderTraversal(TreeNode* root)
{
if(root == NULL) return vector<int>();
inorderTraversal(root->left);
res.push_back(root->val);
inorderTraversal(root->right);
return res;
}
};
迭代
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> call;
if(root != NULL) call.push(root);
while(!call.empty())
{
TreeNode* cur = call.top();
call.pop();
if(cur != NULL)
{
if(cur->right) call.push(cur->right);
call.push(cur);
call.push(NULL);
if(cur->left) call.push(cur->left);
}
else
{
res.push_back(call.top()->val);
call.pop();
}
}
return res;
}
};
后序遍历
递归解法
这里也是很直接的递归思路:一般结点先访问左结点,再依次访问右、根结点;空结点返回空vector,然后再将思路反过来实现代码。
class Solution {
public:
vector<int> res;
vector<int> postorderTraversal(TreeNode* root)
{
if(root == NULL) return vector<int>();
postorderTraversal(root->left);
postorderTraversal(root->right);
res.push_back(root->val);
return res;
}
};
迭代
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> call;
if(root != NULL) call.push(root);
while(!call.empty())
{
TreeNode* cur = call.top();
call.pop();
if(cur != NULL)
{
call.push(cur);
call.push(NULL);
if(cur->right) call.push(cur->right);
if(cur->left) call.push(cur->left);
}
else
{
res.push_back(call.top()->val);
call.pop();
}
}
return res;
}
};