I tried two comparison methods, and did not get expected result.
The first comparison method is inside of a customized class MyTreeNode
as operator<
; The second one is a new comparison class compare
with an override method operator()(MyTreeNode*)
.
The code is shown below. Both outputs are:
5 6 1
while the expected order should be 1 5 6.
The rule for the ordering is: If two nodes have the same x
, then the node with a larger y
value comes first. If nodes have equal both x
and y
, then the node with less treeNode->val
comes first.
So, can anyone help explain it for me ? Thanks
#include <vector>
#include <cstddef>
#include <algorithm>
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x) {}
};
class MyTreeNode{
public:
TreeNode* treeNode;
int x;
int y;
public:
MyTreeNode(TreeNode* node, int _x, int _y): treeNode(node), x(_x), y(_y){
}
//Solution 1.
bool operator<(MyTreeNode& node){
if(x< node.x){
return true;
}
if(x == node.x && y > node.y){
return true;
}
if(x == node.x && y == node.y
&&treeNode->val<node.treeNode->val){
return true;
}
return false;
}
};
//Solution 2
class compare{
public:
bool operator()(MyTreeNode* node1, MyTreeNode* node2){
if(node1->x < node2->x){
return true;
}
if(node1->x == node2->x && node2->y > node1->y){
return true;
}
if(node1->x == node2->x && node2->y == node1->y
&&node1->treeNode->val<node2->treeNode->val){
return true;
}
return false;
}
};
int main(int argc, char* argv[]){
//Solution so;
vector<MyTreeNode*> trees;
trees.push_back(new MyTreeNode(new TreeNode(5), 0, -2)); //A
trees.push_back(new MyTreeNode(new TreeNode(6), 0, -2)); //B
trees.push_back(new MyTreeNode(new TreeNode(1), 0, 0)); //C
//Solution 1
sort (trees.begin(), trees.end());
//Solution 2
//sort (trees.begin(), trees.end(), compare()); // print 5 6 1
// for(int i=0; i<res.size(); i++){
for_each(trees.begin(), trees.end(), [](const MyTreeNode* ele){cout<< " "<< ele->treeNode->val ;});
//}
}
```