【刷题之路】二叉树的前中后序遍历(非递归)

来源:互联网 发布:360防蹭网软件 编辑:程序博客网 时间:2024/06/01 09:24

经典算法

class TreeToSequence {
public:
    vector<vector<int> > convert(TreeNode* root) {
        // write code here
        vector<vector<int> > res;
        res.push_back(fronttree(root));
        res.push_back(midtree(root));
        res.push_back(backtree(root));
        return res;
    }
    vector<int> fronttree(TreeNode* root){
        stack<TreeNode*> temp; //将节点放入栈中操作
        vector<int> res;
        TreeNode* cur;
        temp.push(root);
        while(!temp.empty()){
            cur=temp.top();  //每次循环弹出栈顶节点,并将此节点先压入右子节点,再压入左子节点,重复循环
            temp.pop();
            res.push_back(cur->val);
            if(cur->right) temp.push(cur->right);
            if(cur->left) temp.push(cur->left);
        }
        return res;
    }
    vector<int> midtree(TreeNode* root){
        vector<int> res;
        stack<TreeNode*> temp;
        TreeNode* cur;
        temp.push(root);
        cur=temp.top();
        while(!temp.empty()){
            if(cur!=NULL && cur->left!=NULL){ //一直遍历直到最后一个左子节点
                cur=cur->left;
                temp.push(cur);
            }
            else{
                cur=temp.top();  //当前栈顶节点左子结点为空,则弹出栈顶元素,判断该节点的右子节点是否为空
                res.push_back(cur->val); 
                temp.pop();   //简单来说,压入时判断左子节点是否为空,弹出是判断右子节点是否为空
                cur=cur->right;
                if(cur) temp.push(cur);
            }
        }
        return res;
    }
    vector<int> backtree(TreeNode* root){
        vector<int> res;
        stack<TreeNode*> temp1;  //两个栈配合操作
        stack<TreeNode*> temp2;
        TreeNode* cur;
        temp1.push(root);
        while(!temp1.empty()){
            cur=temp1.top();   //1栈顶元素一直压入1栈
            temp1.pop();
            temp2.push(cur);  
            if(cur->left) temp1.push(cur->left);  //若1栈顶元素有孩子,则按左右顺序押入1栈,重复操作
            if(cur->right) temp1.push(cur->right);  
        } 
        while(!temp2.empty()){     //将2栈元素弹出,即为后序遍历
            res.push_back(temp2.top()->val);
            temp2.pop();
        }
        return res;
    }
};

0 0
原创粉丝点击