【树】B021_两数之和 IV - 输入 BST(set | 中序遍历 + 双指针)

一、题目描述

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.

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True

二、题解

方法一:set + x 序遍历

* 注:不能把 map.put(root.val),因为先放去,如果 sum - root.val 刚好等于这个数的补数,树只有一个结点的时候,你是找不到两个数的。

Set<Integer> set;
int sum;
boolean exist = false;
public boolean findTarget(TreeNode root, int k) {
  set = new HashSet<>();
  sum = k;
  dfs(root);
  return exist;
}
private void dfs(TreeNode root) {
  if (root == null)
      return;
  if (set.contains(sum - root.val)) {
      exist = true;
      return;
  }
  set.add(root.val);
  dfs(root.left);
  dfs(root.right);
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( n ) O(n)

方法二:中序遍历 + 双指针(没想道)

中序遍历一次 BST 会得到一个有序的序列,然后通过双指针找回比较快。没想道的原因是: * 没有读清楚题目(输入的 BST)

List<Integer> arr;
public boolean findTarget(TreeNode root, int k) {
  arr = new ArrayList<>();
  inOr(root);
  int l = 0, r = arr.size()-1;

  while (l < r) {
    int sum = arr.get(l) + arr.get(r);
    if (sum > k)      r--;
    else if (sum < k) l++;
    else return true;
  }
  return false;
}
void inOr(TreeNode root) {
  if (root == null) return;
  inOr(root.left);
  arr.add(root.val);
  inOr(root.right);
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( n ) O(n)
发布了495 篇原创文章 · 获赞 105 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104885718
今日推荐