非递归的前中后序遍历二叉树模板
思路:使用栈模拟递归方法,只不过注意进出的顺序
要点:谁是要遍历的位置的节点,就将它放进去,然后再塞进去个null,
在处理到是Null时,就再拿出一个节点作为当前的值
如果不是Null,那么就按顺序将它的左右子树放进栈
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
//栈写法
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
if (root) stk.push(root);
vector<int> result;
while (!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
if (node != NULL) {
if (node->right) stk.push(node->right);
if (node->left) stk.push(node->left);
stk.push(node);
stk.push(NULL);
}
else {
TreeNode* node = stk.top();
stk.pop();
result.push_back(node->val);
}
}
return result;
}
};
class Solution {
public:
//栈写法
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
if (root) stk.push(root);
vector<int> result;
while (!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
if (node != NULL) {
if (node->right) stk.push(node->right);
stk.push(node);
stk.push(NULL);
if (node->left) stk.push(node->left);
}
else{
TreeNode* node= stk.top();
stk.pop();
result.push_back(node->val);
}
}
return result;
}
};
class Solution {
public:
//栈写法
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
if (root) stk.push(root);
vector<int> result;
while (!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
if (node != NULL) {
stk.push(node);
stk.push(NULL);
if (node->right) stk.push(node->right);
if (node->left) stk.push(node->left);
}
else {
TreeNode* node = stk.top();
stk.pop();
result.push_back(node->val);
}
}
return result;
}
};