Skip to content

Commit

Permalink
another solution
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Jan 15, 2016
1 parent 259a7ab commit 8a30713
Showing 1 changed file with 78 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Source : https://leetcode.com/problems/count-of-smaller-numbers-after-self/
// Author : Calinescu Valentin
// Author : Calinescu Valentin, Hao Chen
// Date : 2015-12-08

/***************************************************************************************
Expand Down Expand Up @@ -73,3 +73,80 @@ class Solution {
return sol;
}
};


/***************************************************************************************
* Another solution - Binary Search Tree
***************************************************************************************/


class BinarySearchTreeNode
{
public:
int val;
int less; // count of members less than val
int count; // count of members equal val
BinarySearchTreeNode *left, *right;
BinarySearchTreeNode(int value) : val(value), less(0),count(1),left(NULL), right(NULL) {}
};

class BinarySearchTree
{
private:
BinarySearchTreeNode* root;
public:
BinarySearchTree(const int value):root(new BinarySearchTreeNode(value)){ }
~BinarySearchTree() {
freeTree(root);
}
void insert(const int value, int &numLessThan) {
insert(root, value, numLessThan);
}
private:
void freeTree(BinarySearchTreeNode* root){
if (root == NULL) return;
if (root->left) freeTree(root->left);
if (root->right) freeTree(root->right);
delete root;
}

void insert(BinarySearchTreeNode* root, const int value, int &numLessThan) {

if(value < root->val) { // left
root->less++;
if(root->left == NULL) {
root->left = new BinarySearchTreeNode(value);
}else{
this->insert(root->left, value, numLessThan);
}
} else if(value > root->val) { // right
numLessThan += root->less + root->count;
if(!root->right) {
root->right = new BinarySearchTreeNode(value);
}else{
this->insert(root->right, value, numLessThan);
}
} else {
numLessThan += root->less;
root->count++;
return;
}
}
};

class Solution {
public:
vector<int> countSmaller(vector<int>& nums) {
vector<int> counts(nums.size());
if(nums.size() == 0) return counts;

BinarySearchTree tree(nums[nums.size()-1]);

for(int i = nums.size() - 2; i >= 0; i--) {
int numLessThan = 0;
tree.insert( nums[i], numLessThan);
counts[i] = numLessThan;
}
return counts;
}
};

0 comments on commit 8a30713

Please sign in to comment.