• 【手撕】中序遍历二叉树


    #include<iostream>
    #include<vector>
    #include<stack>
    
    using namespace std;
    
    struct TreeNode // 定义树节点的结构
    {
        int val;
        TreeNode* left;
        TreeNode* right;
        TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    };
    
    
    /*
    class Solution // 中序遍历二叉树,迭代解法
    {
    public:
        vector<int> result;
        vector<int> preorderTraversal(TreeNode* root) // 中序遍历二叉树,返回的是数组
        {
            if (root == nullptr)
            {
                return {};
            }
            preorderTraversal(root->left);
            result.push_back(root->val);
            preorderTraversal(root->right);
    
            return result;
        }
    };
    */
    
    class Solution //递归解法
    {
    public:
        vector<int> preorderTraversal(TreeNode* root)
        {
            stack<TreeNode*> sta;
            vector<int> result;
            if (root == nullptr)
            {
                return {};
            }
            TreeNode* cur = root;
            while (cur != nullptr || !sta.empty())
            {
                if (cur != nullptr)
                {
                    sta.push(cur);
                    cur = cur->left;
                }
                else
                {
                    cur = sta.top();
                    sta.pop();
                    result.push_back(cur->val);
                    cur = cur->right;
                }
            }
            
            return result;
        }
    };
    
    int main()
    {
        TreeNode* node1 = new TreeNode(1);
        TreeNode* node2 = new TreeNode(2);
        TreeNode* node3 = new TreeNode(3);
        node1->right = node2;
        node2->left = node3;
        TreeNode* root = node1;
        
        vector<int> res;
        Solution solution;
        res = solution.preorderTraversal(root);
    
        vector<int>::iterator iter = res.begin();
        while (iter != res.end())
        {
            cout << *iter << endl;
            iter++;
        }
    
        return 0;
    }
  • 相关阅读:
    HDU.6681.Rikka with Cake(欧拉公式 树状数组)
    Codeforces.449C.Willem, Chtholly and Seniorious(ODT)
    2017-2018 ACM-ICPC, Asia Daejeon Regional Contest (E,G,H,I,K)
    CF GYM.101987A.Circuits(线段树)
    2018-2019 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2018)
    220
    219
    218
    217
    216
  • 原文地址:https://www.cnblogs.com/masbay/p/14197155.html
Copyright © 2020-2023  润新知