Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Idiomatic rust #1505

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions codes/rust/include/list_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl<T> ListNode<T> {
for item in array.iter().rev() {
let node = Rc::new(RefCell::new(ListNode {
val: *item,
next: head.clone(),
next: head.take(),
}));
head = Some(node);
}
Expand All @@ -44,14 +44,14 @@ impl<T> ListNode<T> {
T: std::hash::Hash + Eq + Copy + Clone,
{
let mut hashmap = HashMap::new();
if let Some(node) = linked_list {
let mut current = Some(node.clone());
while let Some(cur) = current {
let borrow = cur.borrow();
hashmap.insert(borrow.val.clone(), cur.clone());
current = borrow.next.clone();
}
let mut node = linked_list;

while let Some(cur) = node {
let borrow = cur.borrow();
hashmap.insert(borrow.val.clone(), cur.clone());
node = borrow.next.clone();
}

hashmap
}
}
22 changes: 10 additions & 12 deletions codes/rust/include/tree_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,23 +72,21 @@ pub fn vec_to_tree(arr: Vec<Option<i32>>) -> Option<Rc<RefCell<TreeNode>>> {
}

/* 将二叉树序列化为列表:递归 */
fn tree_to_vec_dfs(root: Option<Rc<RefCell<TreeNode>>>, i: usize, res: &mut Vec<Option<i32>>) {
if root.is_none() {
return;
fn tree_to_vec_dfs(root: Option<&Rc<RefCell<TreeNode>>>, i: usize, res: &mut Vec<Option<i32>>) {
if let Some(root) = root {
// i + 1 is the minimum valid size to access index i
while res.len() < i + 1 {
res.push(None);
}
res[i] = Some(root.borrow().val);
tree_to_vec_dfs(root.borrow().left.as_ref(), 2 * i + 1, res);
tree_to_vec_dfs(root.borrow().right.as_ref(), 2 * i + 2, res);
}
let root = root.unwrap();
// i + 1 is the minimum valid size to access index i
while res.len() < i + 1 {
res.push(None);
}
res[i] = Some(root.borrow().val);
tree_to_vec_dfs(root.borrow().left.clone(), 2 * i + 1, res);
tree_to_vec_dfs(root.borrow().right.clone(), 2 * i + 2, res);
}

/* 将二叉树序列化为列表 */
pub fn tree_to_vec(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<i32>> {
let mut res = vec![];
tree_to_vec_dfs(root, 0, &mut res);
tree_to_vec_dfs(root.as_ref(), 0, &mut res);
res
}