这类题属于面试常考题,递归法实现容易,尤其要注意迭代法。
前序遍历
递归法
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:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
vector<int> res;
if (!root) return res;
stk.push(root);
while (stk.size())
{
auto t = stk.top();
stk.pop();
res.push_back(t->val);
if (t->right) stk.push(t->right); //栈是先进后出,所以右节点先进
if (t->left) stk.push(t->left);
}
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;
}
};
迭代法
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
auto p = root;
while (p || stk.size()) //p指针不为空或栈不为空
{
if (p) //往左子树走
{
stk.push(p);
p = p->left;
}
else //左子树没有了,回退同时往右子树走
{
p = stk.top();
stk.pop();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};
后序遍历
递归法
class Solution {
public:
void dfs(TreeNode* root, vector<int>& res)
{
if (!root) return;
dfs(root->left, res);
dfs(root->right, res);
res.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
dfs(root, res);
return res;
}
};
迭代法
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
vector<int> res;
if (!root) return res;
stk.push(root);
while (stk.size())
{
auto t = stk.top();
stk.pop();
res.push_back(t->val);
if (t->left) stk.push(t->left);
if (t->right) stk.push(t->right);
}
reverse(res.begin(), res.end()); //最后要翻转
return res;
}
};