Skip to main content
Back to problems
#1214
Medium Algorithms

Two sum bsts

Two Pointers Binary Search Stack Tree Depth-First Search Binary Search Tree Binary Tree
68.2% acceptance
Mar 31, 2026
578
46

No description available.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
use std::rc::Rc;
use std::cell::RefCell;

impl Solution {
  pub fn two_sum_bs_ts(root1: Option<Rc<RefCell<TreeNode>>>, root2: Option<Rc<RefCell<TreeNode>>>, target: i32) -> bool {
    let mut set = std::collections::HashSet::new();
    fn collect(node: &Option<Rc<RefCell<TreeNode>>>, set: &mut std::collections::HashSet<i32>) {
      if let Some(n) = node {
        let n = n.borrow();
        set.insert(n.val);
        collect(&n.left, set);
        collect(&n.right, set);
      }
    }
    collect(&root1, &mut set);
    fn search(node: &Option<Rc<RefCell<TreeNode>>>, target: i32, set: &std::collections::HashSet<i32>) -> bool {
      if let Some(n) = node {
        let n = n.borrow();
        if set.contains(&(target - n.val)) { return true; }
        return search(&n.left, target, set) || search(&n.right, target, set);
      }
      false
    }
    search(&root2, target, &set)
  }
}