返回介绍

solution / 0600-0699 / 0653.Two Sum IV - Input is a BST / README

发布于 2024-06-17 01:03:35 字数 10311 浏览 0 评论 0 收藏 0

653. 两数之和 IV - 输入二叉搜索树

English Version

题目描述

给定一个二叉搜索树 root 和一个目标结果 k,如果二叉搜索树中存在两个元素且它们的和等于给定的目标结果,则返回 true

 

示例 1:

输入: root = [5,3,6,2,4,null,7], k = 9
输出: true

示例 2:

输入: root = [5,3,6,2,4,null,7], k = 28
输出: false

 

提示:

  • 二叉树的节点个数的范围是  [1, 104].
  • -104 <= Node.val <= 104
  • 题目数据保证,输入的 root 是一棵 有效 的二叉搜索树
  • -105 <= k <= 105

解法

方法一:哈希表 + DFS

DFS 遍历二叉搜索树,对于每个节点,判断 k - node.val 是否在哈希表中,如果在,则返回 true,否则将 node.val 加入哈希表中。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
    def dfs(root):
      if root is None:
        return False
      if k - root.val in vis:
        return True
      vis.add(root.val)
      return dfs(root.left) or dfs(root.right)

    vis = set()
    return dfs(root)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode() {}
 *   TreeNode(int val) { this.val = val; }
 *   TreeNode(int val, TreeNode left, TreeNode right) {
 *     this.val = val;
 *     this.left = left;
 *     this.right = right;
 *   }
 * }
 */
class Solution {
  private Set<Integer> vis = new HashSet<>();
  private int k;

  public boolean findTarget(TreeNode root, int k) {
    this.k = k;
    return dfs(root);
  }

  private boolean dfs(TreeNode root) {
    if (root == null) {
      return false;
    }
    if (vis.contains(k - root.val)) {
      return true;
    }
    vis.add(root.val);
    return dfs(root.left) || dfs(root.right);
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  bool findTarget(TreeNode* root, int k) {
    unordered_set<int> vis;

    function<bool(TreeNode*)> dfs = [&](TreeNode* root) {
      if (!root) {
        return false;
      }
      if (vis.count(k - root->val)) {
        return true;
      }
      vis.insert(root->val);
      return dfs(root->left) || dfs(root->right);
    };
    return dfs(root);
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func findTarget(root *TreeNode, k int) bool {
  vis := map[int]bool{}
  var dfs func(*TreeNode) bool
  dfs = func(root *TreeNode) bool {
    if root == nil {
      return false
    }
    if vis[k-root.Val] {
      return true
    }
    vis[root.Val] = true
    return dfs(root.Left) || dfs(root.Right)
  }
  return dfs(root)
}
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 *   }
 * }
 */

function findTarget(root: TreeNode | null, k: number): boolean {
  const dfs = (root: TreeNode | null) => {
    if (!root) {
      return false;
    }
    if (vis.has(k - root.val)) {
      return true;
    }
    vis.add(root.val);
    return dfs(root.left) || dfs(root.right);
  };
  const vis = new Set<number>();
  return dfs(root);
}
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//   TreeNode {
//     val,
//     left: None,
//     right: None
//   }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::{ HashSet, VecDeque };
impl Solution {
  pub fn find_target(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> bool {
    let mut set = HashSet::new();
    let mut q = VecDeque::new();
    q.push_back(root);
    while let Some(node) = q.pop_front() {
      if let Some(node) = node {
        let mut node = node.as_ref().borrow_mut();
        if set.contains(&node.val) {
          return true;
        }
        set.insert(k - node.val);
        q.push_back(node.left.take());
        q.push_back(node.right.take());
      }
    }
    false
  }
}

方法二:哈希表 + BFS

与方法一类似,只是使用 BFS 遍历二叉搜索树。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉搜索树的节点个数。

# Definition for a binary tree node.
# class TreeNode:
#   def __init__(self, val=0, left=None, right=None):
#     self.val = val
#     self.left = left
#     self.right = right
class Solution:
  def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
    q = deque([root])
    vis = set()
    while q:
      for _ in range(len(q)):
        node = q.popleft()
        if k - node.val in vis:
          return True
        vis.add(node.val)
        if node.left:
          q.append(node.left)
        if node.right:
          q.append(node.right)
    return False
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *   TreeNode() {}
 *   TreeNode(int val) { this.val = val; }
 *   TreeNode(int val, TreeNode left, TreeNode right) {
 *     this.val = val;
 *     this.left = left;
 *     this.right = right;
 *   }
 * }
 */
class Solution {
  public boolean findTarget(TreeNode root, int k) {
    Deque<TreeNode> q = new ArrayDeque<>();
    q.offer(root);
    Set<Integer> vis = new HashSet<>();
    while (!q.isEmpty()) {
      for (int n = q.size(); n > 0; --n) {
        TreeNode node = q.poll();
        if (vis.contains(k - node.val)) {
          return true;
        }
        vis.add(node.val);
        if (node.left != null) {
          q.offer(node.left);
        }
        if (node.right != null) {
          q.offer(node.right);
        }
      }
    }
    return false;
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  bool findTarget(TreeNode* root, int k) {
    queue<TreeNode*> q{{root}};
    unordered_set<int> vis;
    while (!q.empty()) {
      for (int n = q.size(); n; --n) {
        TreeNode* node = q.front();
        q.pop();
        if (vis.count(k - node->val)) {
          return true;
        }
        vis.insert(node->val);
        if (node->left) {
          q.push(node->left);
        }
        if (node->right) {
          q.push(node->right);
        }
      }
    }
    return false;
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func findTarget(root *TreeNode, k int) bool {
  q := []*TreeNode{root}
  vis := map[int]bool{}
  for len(q) > 0 {
    for n := len(q); n > 0; n-- {
      node := q[0]
      q = q[1:]
      if vis[k-node.Val] {
        return true
      }
      vis[node.Val] = true
      if node.Left != nil {
        q = append(q, node.Left)
      }
      if node.Right != nil {
        q = append(q, node.Right)
      }
    }
  }
  return false
}
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 *   }
 * }
 */

function findTarget(root: TreeNode | null, k: number): boolean {
  const q = [root];
  const vis = new Set<number>();
  while (q.length) {
    for (let n = q.length; n; --n) {
      const { val, left, right } = q.shift();
      if (vis.has(k - val)) {
        return true;
      }
      vis.add(val);
      left && q.push(left);
      right && q.push(right);
    }
  }
  return false;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文