二叉树的迭代遍历统一写法

前序遍历

leetocde144

  • 思路:由于是要前序遍历存储在result数组中,那么存入栈的顺序就应该是相反的。
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> result;
        if (root != nullptr) st.push(root);
        while(!st.empty())
        {
            TreeNode* node = st.top();
            if(node != nullptr)
            {
                st.pop();
                //right
                if(node->right != nullptr) st.push(node->right);
                //left
                if(node->left != nullptr) st.push(node->left);
                //middle
          
          
                st.push(node);
                st.push(nullptr);
            }else
            {
                st.pop();
                node = st.top();
                st.pop();
                result.push_back(node->val);
            }    
        }
        return result;
    }
};

中序遍历

  • 思路:由于是要中序遍历存储在result数组中的顺序为左中右,那么存入栈的顺序就应该是相反的,从而在弹出栈时能够以左中右的顺序弹出。
    leetcode94
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> st;
        if(root != nullptr) st.push(root);
        
        while(!st.empty())
        {
            TreeNode* node = st.top();           
            if(node != nullptr)
            {
                st.pop();
                if(node->right != nullptr) st.push(node->right);
                st.push(node);
                st.push(nullptr);
                if(node->left != nullptr) st.push(node->left);
            }else
            {
                st.pop(); 
                result.push_back(st.top()->val);
                st.pop();
            }
        }
        return result;
    }
};

后序遍历

  • 思路:由于是要后序遍历存储在result数组中的顺序为左右中,那么存入栈的顺序就应该是相反的,从而在弹出栈时能够以左右中的顺序弹出。
    leetcode145
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> st;
        if(root != nullptr) st.push(root);
        
        while(!st.empty())
        {
            TreeNode* node = st.top();           
            if(node != nullptr)
            {
                st.pop();
                
                st.push(node);
                st.push(nullptr);
                if(node->right != nullptr) st.push(node->right);
                if(node->left != nullptr) st.push(node->left);
            }else
            {
                st.pop(); 
                result.push_back(st.top()->val);
                st.pop();
            }
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值