use std::rc::Rc;
use std::cell::RefCell;
// Tree node with children
#[derive(Debug)]
struct TreeNode {
val: i32,
children: Vec<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
fn new(val: i32) -> Rc<RefCell<Self>> {
Rc::new(RefCell::new(TreeNode { val, children: vec![] }))
}
}
// Linked list node
#[derive(Debug)]
struct ListNode {
val: i32,
next: Option<Box<ListNode>>,
}
impl ListNode {
fn new(val: i32) -> Self {
ListNode { val, next: None }
}
}
// Print tree with indentation
fn print_tree(node: Rc<RefCell<TreeNode>>, depth: usize) {
for _ in 0..depth {
print!(" ");
}
println!("{}", node.borrow().val);
for child in &node.borrow().children {
print_tree(Rc::clone(child), depth + 1);
}
}
// Print array
fn print_array(arr: &[i32]) {
print!("[");
for (i, val) in arr.iter().enumerate() {
if i > 0 { print!(","); }
print!("{}", val);
}
println!("]");
}
// Print linked list
fn print_linked_list(head: &Option<Box<ListNode>>) {
let mut curr = head;
while let Some(node) = curr {
print!("{}", node.val);
if node.next.is_some() {
print!(" -> ");
}
curr = &node.next;
}
println!(" -> null");
}
fn main() {
// Build tree
let root = TreeNode::new(1);
let node2 = TreeNode::new(2);
let node3 = TreeNode::new(3);
let node4 = TreeNode::new(4);
let node5 = TreeNode::new(5);
root.borrow_mut().children.push(Rc::clone(&node2));
root.borrow_mut().children.push(Rc::clone(&node3));
node2.borrow_mut().children.push(Rc::clone(&node4));
node2.borrow_mut().children.push(Rc::clone(&node5));
println!("Tree:");
print_tree(Rc::clone(&root), 0);
// Build array
let arr = vec![1, 2, 3, 4, 5];
println!("\nArray:");
print_array(&arr);
// Build linked list
let mut head = Box::new(ListNode::new(1));
let mut curr = &mut head;
for &val in &[2, 3, 4, 5] {
curr.next = Some(Box::new(ListNode::new(val)));
curr = curr.next.as_mut().unwrap();
}
println!("\nLinked List:");
print_linked_list(&Some(head));
}
root.borrow_mut().children.push(Rc::clone(&node2));
root.borrow_mut().children.push(Rc::clone(&node3));
attach children 2 and 3 to root 1 to build tree hierarchy
node2.borrow_mut().children.push(Rc::clone(&node4));
node2.borrow_mut().children.push(Rc::clone(&node5));
attach children 4 and 5 to node 2 to continue tree hierarchy
print_tree(Rc::clone(&root), 0);
recursively print tree with indentation to show hierarchy
let arr = vec![1, 2, 3, 4, 5];
print_array(&arr);
store nodes in array to show linear order without hierarchy
curr.next = Some(Box::new(ListNode::new(val)));
curr = curr.next.as_mut().unwrap();
link nodes one by one to form linked list sequence
print_linked_list(&Some(head));
print linked list linearly showing sequence
Tree:
1
2
4
5
3
Array:
[1,2,3,4,5]
Linked List:
1 -> 2 -> 3 -> 4 -> 5 -> null