Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
方法一将BST中的每一个结点的值存储在数组中,由于我们已经在Leetcode371中实现有序数组中的计算,因此可以采用如下代码来实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/*计算BST中对应的结点个数*/
int NodeNums(struct TreeNode* root)
{
if(NULL == root)
return 0;
return NodeNums(root->left) + NodeNums(root->right) + 1;
}
/*将结点转换成数组*/
void BST2Array(struct TreeNode* root, int* array, int* pos)
{
if(NULL == root)
return;
BST2Array(root->left, array, pos);
array[(*pos)++] = root->val;
BST2Array(root->right, array, pos);
}
bool findTarget(struct TreeNode* root, int k)
{
if(NULL == root)
return false;
int nodeNums = NodeNums(root);
int* nodes = (int*)malloc(sizeof(int)*nodeNums);
int pos = 0;
BST2Array(root, nodes, &pos);
int low = 0, high = nodeNums-1;
while(low < high)
{
int temp = nodes[low] + nodes[high];
if(k == temp)
return true;
else if(k < temp)
high--;
else low++;
}
/*释放申请的内存*/
free(nodes);
return false;
}