Skip to content

Instantly share code, notes, and snippets.

@qianyan
Created March 15, 2020 13:41
Show Gist options
  • Save qianyan/d351a385dd50e90ca26bbfe13665aa2d to your computer and use it in GitHub Desktop.
Save qianyan/d351a385dd50e90ca26bbfe13665aa2d to your computer and use it in GitHub Desktop.
pub mod two_sum_bst {
use std::rc::Rc;
use std::cell::RefCell;
#[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
}
}
}
pub fn find_target(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> bool {
// transform TreeNode to sorted seq.
let v = to_vec(&root);
println!("the vec is {:?}", v);
two_sum2(v, k)
}
fn two_sum2(numbers: Vec<i32>, target: i32) -> bool {
for i in 0..numbers.len() {
if let Some(j) = &numbers[(i+1)..].binary_search(&(target - numbers[i])).ok() {
return true;
}
}
false
}
fn to_vec(root: &Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
match root {
Some(r) => {
let mut v = to_vec(&r.borrow_mut().left);
v.extend(vec![r.borrow_mut().val]);
v.extend(to_vec(&r.borrow_mut().right));
v
}
None => vec![]
}
}
#[test]
fn test_two_sum_bst() {
let root = Some(Rc::new(
RefCell::new(
TreeNode{val: 7,
left: Some(Rc::new(
RefCell::new(
TreeNode::new(2)))),
right: Some(Rc::new(
RefCell::new(
TreeNode{ val: 11,
left: None,
right: Some(Rc::new(
RefCell::new(
TreeNode::new(15))))}
)))
})));
let found = find_target(root, 26);
assert_eq!(found, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment