两数之和的第四个版本:输入是一颗二叉查找树。
首先讲一下我的解法:
二叉查找树的一个重要特点是其中序遍历的结果是一个有序数组。我们可以很好的利用该性质:首先得到BST的中序遍历结果,然后采用167. Two Sum II - Input array is sorted中的方法进行搜索,找到返回true,否则返回false。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
ArrayList<Integer> nums = new ArrayList<Integer>();
inOrder(root,nums);
//设置两端的指针,进行搜索
for(int i=0,j=nums.size()-1;i<j;)
{
if(nums.get(i) + nums.get(j) == k) return true;
else if(nums.get(i) + nums.get(j) > k) j--;
else i++;
}
return false;
}
//中序遍历得到BST的有序序列
public void inOrder(TreeNode root,ArrayList<Integer> nums)
{
if(root == null) return;
inOrder(root.left,nums);
nums.add(root.val);
inOrder(root.right,nums);
}
}
这种方法的时间复杂度为O(n),空间复杂度为O(n)。
我们再来看一下leetcode上面给出的solution。
1.使用HashSet
2.使用广度优先搜索(BFS)和HashSet
3.利用BST的性质
这种方法即是我所采用的方法,上面已经给出解答,这里不再详述。