数据结构之二叉树:先中后序遍历(非递归)

来源:互联网 发布:linux系统压缩命令 编辑:程序博客网 时间:2024/05/08 13:42

请用非递归方式实现二叉树的先序、中序和后序的遍历打印。

给定一个二叉树的根结点root,请依次返回二叉树的先序,中序和后续遍历(二维数组的形式)。



先序遍历(MLR):用一个栈实现   

中序遍历(LMR):用一个栈实现    

后序遍历(LRM):用两个栈实现   



代码(不包括main函数):


class TreeToSequence {
public:
    vector<vector<int> > convert(TreeNode* root) {
        // write code here
        vector<int>vec1;
        vector<int>vec2;
        vector<int>vec3;
        MLR(root,vec1);
        LMR(root,vec2);
        LRM(root,vec3);
        vector<vector<int> > result;
        result.push_back(vec1);
        result.push_back(vec2);
        result.push_back(vec3);
        return result;
    }
    
    
    void MLR(TreeNode *root,vector<int>&vec){
        if(root==NULL) return;
        stack<TreeNode*>s;
        s.push(root);
        auto cur=s.top();
        while(!s.empty()){     //循环的条件之前写的是cur!=NULL 判我错误                                
            s.pop();                 //可能是不是栈弹完了 cur指不了 还是什么原因 以后避免这样
            vec.push_back(cur->val);
            if(cur->right){
                s.push(cur->right);
            }
            if(cur->left){
                s.push(cur->left);
            }
            cur=s.top();
        }


    }
 
    void LMR(TreeNode *root,vector<int>&vec){
        if(root==NULL) return;
        stack<TreeNode*>s;
        TreeNode* cur=root;


        while(!s.empty() || cur){
            while(cur!=NULL){
               s.push(cur);      //1
               cur=cur->left;   //2      之前把1 2句写反了  总结:一般改变条件的句子 写在最后  
            }   
            TreeNode *node=s.top();
            s.pop();
            vec.push_back(node->val);
            cur=node->right;
        }
    }
    
    void LRM(TreeNode *root,vector<int>&vec){
        if(root==NULL) return;
        stack<TreeNode*>s1,s2;
        s1.push(root);
        while(!s1.empty()){
            auto cur=s1.top();
            s1.pop();
            s2.push(cur);
            if(cur->left){
                s1.push(cur->left);
            }
            if(cur->right){
                s1.push(cur->right);
            }     
        }
        while(!s2.empty()){
            auto p=s2.top();
            s2.pop();
            vec.push_back(p->val);
        }
    }
    
};

1 0
原创粉丝点击