【本文链接】
http://www.cnblogs.com/hellogiser/p/kmin-of-array-vs-kmin-of-bst.html
【分析】
数组的Kmin算法和二叉搜索树的Kmin算法非常类似,其本质是找序列中的第K大或者第K小的元素,可以借鉴QuickSort的思想加以实现。
【Kmin_of_Array】
C++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
// 70_Kmin_of_Array_and_BST.cpp : Defines the entry point for the console application. // /* version: 1.0 author: hellogiser blog: http://www.cnblogs.com/hellogiser date: 2014/9/18 */ #include "stdafx.h" void print(int *a, int n) int compare_less (const void *a, const void *b) //======================================================== int partition1(int *a, int left, int right) int kmin(int *a, int left, int right, int k) int Kmin_of_Array(int *a, int n, int k) void test_base(int *a, int n, int k) void test_default() void test_main() int _tmain(int argc, _TCHAR *argv[]) |
【Kmin_of_BST】
C++ Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
//======================================================== // kmin of bst //======================================================== // binary tree node struct struct BinaryTreeNode { int value; BinaryTreeNode *parent; // for rank of bst BinaryTreeNode *left; BinaryTreeNode *right; int size; // for kmin of bst // x.size = x.left.size + x.right.size +1 }; int node_size(BinaryTreeNode *node) int left_size(BinaryTreeNode *node) BinaryTreeNode *kmin_bst(BinaryTreeNode *root, int k) int pk = left_size(root) + 1; // get node rank first if (k == pk) BinaryTreeNode *Kmin_of_BST(BinaryTreeNode *root, int k) |