首页 > 其他 > 详细

二叉树的迭代遍历

时间:2020-11-08 17:05:37      阅读:31      评论:0      收藏:0      [点我收藏+]

前序:

//前序1
    vector<int> preorderTraversal(TreeNode* root) {
        if(!root) return {};
        vector<int> ans;
        vector<TreeNode*> stack;
        TreeNode* cur;
        stack.push_back(root);
        //前序为中左右,先压入右子树
        while(!stack.empty()){
            cur=stack.back();
            stack.pop_back();
            ans.push_back(cur->val);
            if(cur->right){
                stack.push_back(cur->right);
            }
            if(cur->left){
                stack.push_back(cur->left);
            }
        }
        return ans;
    }
//前序2(中序改的)
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        vector<TreeNode*> stack;
        TreeNode* cur=root;
        while(cur||!stack.empty()){
            while(cur){
                ans.push_back(cur->val);
                stack.push_back(cur);
                cur=cur->left;
            }
            cur=stack.back();
            stack.pop_back();
            cur=cur->right;
        }
        return ans;
    }

 

中序

//中序
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        vector<TreeNode*> stack;
        TreeNode* cur=root;
        while(cur||!stack.empty()){
            while(cur){
                stack.push_back(cur);
                cur=cur->left;
            }
            cur=stack.back();
            stack.pop_back();
            ans.push_back(cur->val);
            cur=cur->right;
        }
        return ans;
    }

 

后序

//后序(左右中),将前序遍历(左右中)的左右反转,压入栈中输出
    //后序(前序1改的)
    vector<int> preorderTraversal(TreeNode* root) {
        if(!root) return {};
        vector<int> ans;
        vector<TreeNode*> stack;
        vector<int> houxu;
        TreeNode* cur;
        stack.push_back(root);
        //后序为左右中,先压入左子树
        while(!stack.empty()){
            cur=stack.back();
            stack.pop_back();
            houxu.push_back(cur->val);
            if(cur->left){
                stack.push_back(cur->left);
            }
            if(cur->right){
                stack.push_back(cur->right);
            }
        }
        for(int i=houxu.size()-1;i>=0;i--){
            ans.push_back(houxu[i]);
        }
        return ans;
    }

 

二叉树的迭代遍历

原文:https://www.cnblogs.com/Zzzjc/p/13944358.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!