Created
June 13, 2026 09:58
-
-
Save ozzyozbourne/6630fa826240e1d04f412a1e9e1fe424 to your computer and use it in GitHub Desktop.
reference counted tree pruning example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::{rc::Rc, cell::RefCell}; | |
| #[derive(Debug)] | |
| struct TreeNode { | |
| val: i32, | |
| left: Option<Rc<RefCell<TreeNode>>>, | |
| right: Option<Rc<RefCell<TreeNode>>> | |
| } | |
| impl Drop for TreeNode { fn drop(&mut self) { println!(">>> Free Node {}", self.val); } } | |
| fn node(val: i32, left: Option<Rc<RefCell<TreeNode>>>, right: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> { | |
| Some(Rc::new(RefCell::new(TreeNode { val, left, right }))) | |
| } | |
| fn main() { | |
| let (n4, n5, n6, n7) = (node(4, None, None), node(5, None, None), node(6, None, None), node(7, None, None)); | |
| let (n2, n3) = (node(2, n4, n5), node(3, n6, n7)); | |
| let root = node(1, n2, n3); | |
| let keep = root.as_ref().unwrap().borrow().left.clone(); | |
| println!("count on n2: {}", Rc::strong_count(&keep.as_ref().unwrap())); | |
| println!("dropping root"); | |
| drop(root); | |
| println!("count on n2: {}", Rc::strong_count(&keep.as_ref().unwrap())); | |
| println!("the left tree value are also usable {} {}", | |
| keep.as_ref().unwrap().borrow().left.as_ref().unwrap().borrow().val, | |
| keep.as_ref().unwrap().borrow().right.as_ref().unwrap().borrow().val | |
| ); | |
| println!("exiting the main"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment