SHARE
TWEET

Untitled

a guest May 23rd, 2019 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use::std::rc::Rc;
  2. use::std::cell::RefCell;
  3.  
  4. #[derive(Debug)]
  5. struct TreeNode {
  6.     pub val: i32,
  7.     pub left: Option<Rc<RefCell<TreeNode>>>,
  8.     pub right: Option<Rc<RefCell<TreeNode>>>,
  9. }
  10.  
  11. fn preorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
  12.     let order: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(Vec::new()));
  13.     fn recurse(node: Option<Rc<RefCell<TreeNode>>>, a: Rc<RefCell<Vec<i32>>>) {
  14.         if let Some(n) = node {
  15.             a.borrow_mut().push(n.borrow().val);
  16.             if let Some(left_n) = &n.borrow().left {
  17.                 recurse(Some(Rc::clone(left_n)), Rc::clone(&a));
  18.             } if let Some(right_n) = &n.borrow().right {
  19.                 recurse(Some(Rc::clone(right_n)), Rc::clone(&a));
  20.             };
  21.         };
  22.     }
  23.     recurse(root, Rc::clone(&order));
  24.     match Rc::try_unwrap(order) {
  25.         Ok(ref_cell) => {
  26.             ref_cell.into_inner()
  27.         },
  28.         Err(err) => panic!("{:?}", err),
  29.     }
  30. }
  31.  
  32.  
  33. fn main () {
  34.     let case = TreeNode {
  35.         val: 2,
  36.         left: Some(Rc::new(RefCell::new(TreeNode {
  37.             val: 3,
  38.             left: None,
  39.             right: Some(Rc::new(RefCell::new(TreeNode{
  40.                 val: 5,
  41.                 left: None,
  42.                 right: Some(Rc::new(RefCell::new(TreeNode{
  43.                     val: 4,
  44.                     left: None,
  45.                     right: None,
  46.                 }))),
  47.             }))),
  48.         }))),
  49.         right: Some(Rc::new(RefCell::new(TreeNode {
  50.             val: 1,
  51.             left: None,
  52.             right: None,
  53.         }))),
  54.     };
  55.     // let case = TreeNode {
  56.     //     val: 1,
  57.     //     left: None,
  58.     //     right: Some(Rc::new(RefCell::new(TreeNode {
  59.     //         val: 2,
  60.     //         right: None,
  61.     //         left: Some(Rc::new(RefCell::new(TreeNode{
  62.     //             val: 3,
  63.     //             right: None,
  64.     //             left: None,
  65.     //         }))),
  66.     //     }))),
  67.     // };
  68.     println!("{:?}", preorder_traversal(Some(Rc::new(RefCell::new(case)))));
  69. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top