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


    #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 {};
            }
            result.push_back(root->val);
            preorderTraversal(root->left);
            preorderTraversal(root->right);
    
            return result;
        }
    };
    */
    
    class Solution //递归解法
    {
    public:
        vector<int> preorderTraversal(TreeNode* root)
        {
            stack<TreeNode*> sta;
            vector<int> result;
            if (root != nullptr)
            {
                sta.push(root);
            }
            while (!sta.empty())
            {
                int size = sta.size();
                for (int i = 0; i < size; i++)
                {
                    TreeNode* node = sta.top();
                    sta.pop();
                    result.push_back(node->val);
                    if (node->right)
                    {
                        sta.push(node->right);
                    }
                    if (node->left)
                    {
                        sta.push(node->left);
                    }
                }
                
            }
            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;
    }
  • 相关阅读:
    ASP.NET Core中的Action的返回值类型
    ASP.NET Core中的Controller
    ASP.NET Core Authentication and Authorization
    ASP.NET Core
    ASP.NET Core ActionFilter引发的一个EF异常
    使用Github Packages功能上传nuget包到Github
    「每日五分钟,玩转JVM」:线程共享区
    JVM(二):画骨
    Spring Boot 2.x (十八):邮件服务一文打尽
    一道面试题
  • 原文地址:https://www.cnblogs.com/masbay/p/14197108.html
Copyright © 2020-2023  润新知