h*****i 发帖数: 1017 | 1 #include
#include
using namespace std;
class binaryTree {
public:
int value;
int indx;
binaryTree *left;
binaryTree *right;
binaryTree(){
left = NULL;
right = NULL;
}
};
void insert(binaryTree *bTree, int num, int key){
if(bTree == NULL){
bTree = new binaryTree;
bTree->value = num;
bTree->indx = key;
printf("%d %dn",bTree->value,bTree->indx);
return;
}
if(num >= bTree->value){
printf("Insert to the right %dn",num);
insert(bTree->right,num,key);
} else {
insert(bTree->left,num,key);
printf("Insert to the left %dn",num);
}
}
int search(binaryTree *bTree, int num) {
if (bTree == NULL) {
return -1;
}
if (num == bTree->value) {
return bTree->indx;
}
else if (num > bTree->value) {
return search(bTree->right, num);
}
else {
return search(bTree->left, num);
}
}
class Solution {
public:
vector twoSum(vector& nums, int target) {
vector result;
//Construct binary tree
binaryTree *bTree;
bTree = NULL;
for (int i = 0; i < nums.size(); i ++){
insert(bTree,nums[i],i);
printf("Out %dn",bTree->value);
}
//Search
for (int i = 0; i < nums.size(); i ++){
int match = search(bTree,target - nums[i]);
if(match >=0) {
result.push_back(i);
result.push_back(match);
}
}
return result;
}
};
int main()
{
Solution sol;
vector nums;
vector res;
nums[0] = 3;
nums[1] = 2;
nums[2] = 4;
res = sol.twoSum(nums, 6);
for (int i = 0; i < res.size(); i++) {
printf("%dn", res[i]);
}
} | l**g 发帖数: 133 | 2 插入root的时候,并没有有效的赋值
insert操作通常返回插入节点的位置或iterator | T******e 发帖数: 157 | 3 看到insert函数,里面用new产生新node,但函数返回后这些指针都没了,一方面导致
你无法再到达那些node,另一方面就是内存泄漏了 | b********6 发帖数: 35437 | 4 void insert(binaryTree *&bTree, int num, int key)
加个&看能不能解决问题 | u****0 发帖数: 155 | |
|