来自leetcode原题
声明:
有别于教科书的经典非递归实现方式,本文采用模拟系统栈的方式实现非递归,目的是有助于理解递归与栈的紧密关系。并且,三种遍历的代码形式类似,而经典非递归在后序遍历部分较之前两者有很大差异且不易理解。
前序遍历
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct Commend{
string s; //run,print
TreeNode* node;
Commend(string s, TreeNode* node): s(s), node(node){}
};
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> record;
if(!root)
return record;
stack<Commend> stack_Tree;
stack_Tree.push(Commend("run", root));
while(!stack_Tree.empty()){
Commend commend = stack_Tree.top();
stack_Tree.pop();
if(commend.s == "print"){
record.push_back(commend.node->val);
}
else{
assert(commend.s == "run");
if(commend.node->right)
stack_Tree.push(Commend("run", commend.node->right));
if(commend.node->left)
stack_Tree.push(Commend("run", commend.node->left));
stack_Tree.push(Commend("print", commend.node));
}
}
return record;
}
};
中序遍历
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct Commend{
string s;
TreeNode* node;
Commend(string s, TreeNode* node) : s(s), node(node) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> record;
if(!root){
return record;
}
stack<Commend> stack_Tree;
stack_Tree.push(Commend("run", root));
while(!stack_Tree.empty()){
Commend commend = stack_Tree.top();
stack_Tree.pop();
if(commend.s == "print"){
record.push_back(commend.node->val);
}
else{
assert(commend.s == "run");
if(commend.node->right)
stack_Tree.push(Commend("run", commend.node->right));
stack_Tree.push(Commend("print", commend.node));
if(commend.node->left)
stack_Tree.push(Commend("run", commend.node->left));
}
}
return record;
}
};
后序遍历
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct Commend{
string s;
TreeNode* node;
Commend(string s, TreeNode* node) : s(s), node(node) {}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> record;
if(!root){
return record;
}
stack<Commend> stack_Tree;
stack_Tree.push(Commend("run", root));
while(!stack_Tree.empty()){
Commend commend = stack_Tree.top();
stack_Tree.pop();
if(commend.s == "print"){
record.push_back(commend.node->val);
}
else{
assert(commend.s == "run");
stack_Tree.push(Commend("print", commend.node));
if(commend.node->right)
stack_Tree.push(Commend("run", commend.node->right));
if(commend.node->left)
stack_Tree.push(Commend("run", commend.node->left));
}
}
return record;
}
};
本人blog:http://breadhunter.gitee.io