树的前中后序遍历定义:
前:中左右
中:左中右
后:左右中
递归版本非常好写,这里不再赘述,仅考虑非递归使用栈进行遍历
首先来看节点结构
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
以前学的版本
中序
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ret;
stack<TreeNode*> stk;
while (!stk.empty() || root != NULL) {
if (root != NULL) {
stk.push(root);
root = root->left;
}
else {
root = stk.top();
stk.pop();
ret.push_back(root->val);
root = root->right;
}
}
return ret;
}
};
前序
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
stack<TreeNode*> stk;
while (!stk.empty() || root != NULL) {
if (root != NULL) {
ret.push_back(root->val);
stk.push(root);
root = root->left;
}
else {
root = stk.top();
stk.pop();
root = root->right;
}
}
return ret;
}
};
这两种前中序的非递归遍历写法也是主流的写法,差别也仅有ret.push_back(root->val);
访问节点这一句话的位置不同,但这种写法是没有办法写树的后序遍历的。
船新的版本
其核心就是在栈中使用了pair
二元组来标记这是第几次被访问,其实就是完完全全地模拟了递归的写法。
后序:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ret;
stack<pair<TreeNode*, int>> stk;
if (root)
stk.push({root, 0});
while (!stk.empty()) {
pair<TreeNode*, int> cur = stk.top();
if (cur.second == 0) { // 第零次被访问
stk.top().second = 1; // 标记为1
if (cur.first->left)
stk.push({cur.first->left, 0});
}
else if (cur.second == 1) { // 第一次被访问
stk.top().second = 2; // 标记位2
if (cur.first->right)
stk.push({cur.first->right, 0});
}
else if (cur.second == 2) { // 第二次被访问
ret.push_back(cur.first->val);
stk.pop();
}
}
return ret;
}
};
中序:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ret;
stack<pair<TreeNode*, int>> stk;
if (root)
stk.push({root, 0});
while (!stk.empty()) {
pair<TreeNode*, int> cur = stk.top();
if (cur.second == 0) {
stk.top().second = 1;
if (cur.first->left)
stk.push({cur.first->left, 0});
}
else if (cur.second == 1) {
stk.top().second = 2;
ret.push_back(cur.first->val);
}
else if (cur.second == 2) {
stk.pop();
if (cur.first->right)
stk.push({cur.first->right, 0});
}
}
return ret;
}
};
前序
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ret;
stack<pair<TreeNode*, int>> stk;
if (root)
stk.push({root, 0});
while (!stk.empty()) {
pair<TreeNode*, int> cur = stk.top();
if (cur.second == 0) {
stk.top().second = 1;
ret.push_back(cur.first->val);
}
else if (cur.second == 1) {
stk.top().second = 2;
if (cur.first->left)
stk.push({cur.first->left, 0});
}
else if (cur.second == 2) {
stk.pop();
if (cur.first->right)
stk.push({cur.first->right, 0});
}
}
return ret;
}
};