Skip to content

Instantly share code, notes, and snippets.

@spazm
Last active May 1, 2020 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spazm/23727a722bff54fd20f44ef43b96466b to your computer and use it in GitHub Desktop.
Save spazm/23727a722bff54fd20f44ef43b96466b to your computer and use it in GitHub Desktop.
code puzzles
// Provided code
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
val: i32,
left: Option<Rc<RefCell<TreeNode>>>,
right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
use std::cell::RefCell;
use std::rc::Rc;
pub struct Solution {}
impl Solution {
pub fn is_valid_sequence(root: Option<Rc<RefCell<TreeNode>>>, arr: Vec<i32>) -> bool {
pub fn check_tree(root: &Option<Rc<RefCell<TreeNode>>>, arr: &[i32]) -> bool {
//! Uses references to avoid a lot of copy()
//! compared to the interface of check_tree
match (root, arr) {
(None, rx) => rx.is_empty(),
(Some(_), rx) if rx.is_empty() => false,
(Some(t), rx) if t.borrow().val != rx[0] => false,
(Some(t), rx) if rx.len() == 1 => {
let t = t.borrow();
match (&t.left, &t.right) {
(None, None) => true,
(_, _) => false,
}
}
(Some(t), rx) => {
let t = t.borrow();
let rx = &rx[1..];
check_tree(&t.left, rx) || check_tree(&t.right, rx)
}
}
}
check_tree(&root, &arr)
}
}
#[test]
pub fn test_singleton() {
let tree = Some(Rc::new(RefCell::new(TreeNode::new(8))));
let expected = vec![8];
assert!(Solution::is_valid_sequence(tree, expected))
}
#[test]
pub fn test_singlfeton_fail() {
let tree = Some(Rc::new(RefCell::new(TreeNode::new(3))));
let path = vec![8];
assert!(!Solution::is_valid_sequence(tree, path))
}
#[test]
pub fn test_small_tree() {
// grungy hard coding of tree
let left = Some(Rc::new(RefCell::new(TreeNode::new(2))));
let right = Some(Rc::new(RefCell::new(TreeNode::new(3))));
let tree = Some(Rc::new(RefCell::new(TreeNode{val:1, left, right})));
let path = vec![1,2];
let expected = true;
assert!(Solution::is_valid_sequence(tree.clone(), path) == expected);
let path = vec![1,3];
let expected = true;
assert!(Solution::is_valid_sequence(tree.clone(), path) == expected);
let path = vec![1,2,3];
let expected = false;
assert!(Solution::is_valid_sequence(tree.clone(), path) == expected);
let path = vec![1];
let expected = false;
assert!(Solution::is_valid_sequence(tree.clone(), path) == expected);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment