补cpp 8

https://www.cnblogs.com/firstdream/p/8192882.html  转非递归

 

 

1、二叉树(前序)

#include <iostream>
#include <string>

#include <algorithm>
#include <vector> 
#include <stack> 
#include <algorithm> 
#include <functional> 
#include <list>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left),
        right(right) {}
};

//    4
//   2  6
// 1  3 

TreeNode* root5 = new TreeNode(1);
TreeNode* root4 = new TreeNode(3);
TreeNode* root3 = new TreeNode(2,root5,root4);
TreeNode* root2 = new TreeNode(6);
TreeNode* root1 = new TreeNode(4,root3,root2);

void preTraver(TreeNode* root) {
    if (root == NULL) return;
    cout << root->val << endl;
    preTraver(root->left);
    preTraver(root->right);
}

void stackPreTraver(TreeNode* root) {
    stack<TreeNode*> stk;
    TreeNode* curr = root;
    while (!stk.empty()||curr != NULL) {
        while (curr!=NULL)
        {
            cout << curr->val << endl;
            stk.push(curr);
            curr = curr->left;
        }
        curr = stk.top();
        stk.pop();
        curr = curr->right;
    }
}

int main()
{
    //preTraver(root1);
    stackPreTraver(root1);
    return 0;
}

2、qsort

#include <iostream>
#include <string>
#include <algorithm>
#include <vector> 
#include <algorithm> 
#include <functional> 
#include <list>
using namespace std;

void QuickSort(int nums[], int l, int r) {
    if (l + 1 >= r) return;
    int first = l, last = r - 1, key = nums[first];
    while (first < last) {
        while (first < last && nums[last] >= key) last--;
        nums[first] = nums[last];
        while (first < last && nums[first] <= key) first++;
        nums[last] = nums[first];
    }
    nums[first] = key;
    QuickSort(nums, l, first);
    QuickSort(nums, first + 1, r);
}

int main_q()
{
    int a[] = { 0,34,66,2,5,95,4,46,27 };
    QuickSort(a, 0, sizeof(a) / sizeof(int));
    for (int i = 0; i <= 8; ++i) {
        std::cout << a[i] << " "; 
    }
    std::cout << endl;
    return 0;
}

 

posted @ 2022-02-17 09:55  cnchengv  阅读(17)  评论(0编辑  收藏  举报