LeetCode上有三题是直接分别对应二叉树的非递归遍历实现:144/94/145
前序遍历:非递归和递归的方式差不多,主要是要注意左右子节点的入栈顺序和递归时恰好相反
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> rs;
//preorder(root,rs);
if(!root) return rs;
stack<TreeNode*> nodes;
nodes.push(root);
while(!nodes.empty()){
TreeNode* p=nodes.top();
rs.push_back(p->val);
nodes.pop();
if(p->right!=NULL) nodes.push(p->right);
if(p->left!=NULL) nodes.push(p->left);
}
return rs;
}
private:
//递归的方式
void preorder(TreeNode* root,vector<int> &rs){
if(root){
rs.push_back(root->val);
preorder(root->left,rs);
preorder(root->right,rs);
}
}
};
中序:需要一直找左节点入栈
/**
* Definition for a binary tree node.
* 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> rs;
//递归
//inorder(root,rs);
//非递归
stack<TreeNode*> nodes;
while(!nodes.empty()||root){
if(root){
nodes.push(root);
root=root->left;
}else{
root=nodes.top();
nodes.pop();
rs.push_back(root->val);
root=root->right;
}
}
return rs;
}
private:
//递归的方式
void inorder(TreeNode* root,vector<int>& rs){
if(root){
inorder(root->left,rs);
rs.push_back(root->val);
inorder(root->right,rs);
}
}
};
后序遍历:比较复杂
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> rs;
//postorder(root,rs); //递归实现
//非递归实现
stack<TreeNode*> nodes;
if(root) nodes.push(root);
TreeNode* c;
while(!nodes.empty()){
c=nodes.top();
if(c->left&&c->left!=root&&c->right!=root){
nodes.push(c->left);
}else if(c->right&&c->right!=root){
nodes.push(c->right);
}else{
rs.push_back(c->val);
root=c;
nodes.pop();
}
}
return rs;
}
private:
//递归实现
void postorder(TreeNode* root,vector<int>& rs){
if(root){
postorder(root->left,rs);
postorder(root->right,rs);
rs.push_back(root->val);
}
}
};