Created
September 4, 2015 14:44
-
-
Save anonymous/e1db3c854e77334eb318 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains 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
#[derive(Debug)] | |
struct Node<T> { | |
content : T, | |
parent : usize, | |
children : Vec<usize>, | |
} | |
#[derive(Debug)] | |
struct Heiarchy<T> { | |
nodes: Vec<Node<T>>, | |
_current_id : usize, | |
} | |
impl<T> Heiarchy<T> { | |
pub fn new(head_value : T) -> Self { | |
let mut h = Heiarchy { | |
nodes : Vec::new(), | |
_current_id : 1, | |
}; | |
h.nodes.push(Node { content: head_value, parent : 0, children: Vec::new() }); | |
h | |
} | |
pub fn push(&mut self, v : T, parent_id : usize) -> Option<usize> { | |
if parent_id < self.nodes.len() { | |
// it is a valid index, make this the parent node of the node being pushed. | |
self.nodes.push(Node{content: v, parent : parent_id, children : Vec::new() }); | |
self._current_id += 1; | |
// go to the parent node and update the children | |
self.nodes[parent_id].children.push(self._current_id - 1); | |
Some(self._current_id - 1) | |
} else { | |
None | |
} | |
} | |
} | |
impl<T> Heiarchy<T> where T : std::fmt::Debug { | |
pub fn show_node(&self, _id : usize) { | |
self.show_node_rec(_id, 0) | |
} | |
pub fn show_node_rec(&self, _id : usize, depth: usize) { | |
for _ in 0..depth { | |
print!(" | "); | |
} | |
println!("{:?}", self.nodes[_id].content); | |
for &child_id in self.nodes[_id].children.iter() { | |
self.show_node_rec(child_id, depth+1) | |
} | |
} | |
} | |
fn main() { | |
let mut h = Heiarchy::new("The Earth"); | |
let usa_ref = h.push("USA", 0).unwrap(); | |
let china_ref = h.push("China", 0).unwrap(); | |
h.push("Utah", usa_ref); | |
h.push("California", usa_ref); | |
h.push("Guangdong Province", china_ref); | |
h.show_node(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment