二叉树非递归遍历有三种方式:前序遍历、中序遍历、后续遍历
前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode *> s;
while (root || !s.empty()){
while (root){
s.push(root);
res.push_back(root->val);
root = root->left;
}
root = s.top();
s.pop();
root = root->right;
}
return res;
}
};
中序遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode *> s;
while (root || !s.empty()){
while (root){
s.push(root);
root = root->left;
}
root = s.top();
s.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
};
后续遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode *> s;
TreeNode * lastNode = NULL, *topNode = NULL;
while (root || !s.empty()){
while (root){
s.push(root);
root = root->left;
}
topNode = s.top();
// topNode->right != lastNode 表示lastNode 这个节点下面的节点已经遍历过,没有必要再遍历了...
if (topNode->right != NULL && topNode->right != lastNode){
root = topNode->right;
}
else{
res.push_back(topNode->val);
lastNode = topNode;
s.pop();
}
}
return res;
}
};