补cpp 8
https://www.cnblogs.com/firstdream/p/8192882.html 转非递归
1、二叉树(前序)
#include#include <string> #include #include #include #include #include #include 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
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#include <string> #include #include #include #include #include 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; }