037.二叉树非递归遍历

用栈实现非递归遍历

  • 时间复杂度O(n)

  • 空间复杂度O(h) , h为树高

前序

leetcode 144

struct TreeNode{
    int val;
    TreeNode*left;
    TreeNode*right;
    TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};
void preorder(TreeNode*root){
    if(root==nullptr)return;
    stack<TreeNode*>st;
    st.push(root);
    while(!st.empty()){
        TreeNode* cur=st.top();
        st.pop();
        /*
        前序位置
        */
       if(cur->right!=nullptr){
        st.push(cur->right);
       }
       if(cur->left!=nullptr){
        st.push(cur->left);
       }
    }
}

中序

leetcode 94

void inorder(TreeNode*root){
    if(root==nullptr)return;
    stack<TreeNode*>st;
    TreeNode*cur=root;
    while(!st.empty()||cur!=nullptr){
        if(cur!=nullptr){
            st.push(cur);
            cur=cur->left;
        }
        else{
            cur=st.top();
            st.pop();
            /*
            中序位置
            */
           cur=cur->right;
        }
    }
}

后序

leetcode 145

void postorder(TreeNode*root){
    if(root==nullptr)return;
    stack<TreeNode*>st;
    st.push(root);
    while(!st.empty()){
        TreeNode*cur=st.top();
        if(cur->left!=nullptr&&cur->left!=root&&cur->right!=root){
            st.push(cur->left);
        }
        else if(cur->right!=nullptr&&cur->right!=root){
            st.push(cur->right);
        }
        else{
            /*
            后序位置
            */
           root=st.top();
           st.pop();
        }
    }
}
posted @ 2026-01-07 19:43  射杀百头  阅读(1)  评论(0)    收藏  举报