Re: [閒聊] 每日leetcode

作者: yam276 ('_')   2024-05-17 22:38:30
※ 引述《Rushia (早瀬ユウカの体操服 )》之銘言:
: https://leetcode.com/problems/delete-leaves-with-a-given-value/description/
: 1325. Delete Leaves With a Given Value
: 給你一個二元樹和一個數字 target,刪除所有葉子節點是 target 的節點,如果刪除後
: 新的葉子節點也是 target 也要刪除。
: 思路:
: 1.如果遇到葉子節點且是target就刪除他並返回null,每次檢查之間要先dfs,如果dfs
: 返回null就刪除子節點。
糞糙語言
每次遇到樹的題目都會爆行數
恨Rust
Node:
impl Solution {
pub fn remove_leaf_nodes(root: Option<Rc<RefCell<TreeNode>>>, target: i32)
-> Option<Rc<RefCell<TreeNode>>> {
fn remove_leaves(node: Option<Rc<RefCell<TreeNode>>>, target: i32)
-> Option<Rc<RefCell<TreeNode>>> {
if let Some(cur_node) = node {
let left = remove_leaves(cur_node.borrow().
left.clone(),
target);
let right = remove_leaves(cur_node.borrow().
right.clone(),
target);
{ //這個區塊符號用來在使用後釋放borrow,不然後面if會不給用
let mut cur_node_mut = cur_node.borrow_mut();
cur_node_mut.left = left;
cur_node_mut.right = right;
}
if cur_node.borrow().val == target &&
cur_node.borrow().left.is_none() &&
cur_node.borrow().right.is_none() {
return None;
}
else {
return Some(cur_node);
}
}
None
}
remove_leaves(root, target)
}
}
作者: steven183 (steven183183)   2023-05-17 22:38:00
別卷了
作者: yam276 ('_')   2024-05-17 22:39:00
好討厭Option<Rc<RefCell<obj>>>
作者: aioiwer318 (哀歐)   2024-05-17 22:39:00
別卷了
作者: sustainer123 (caster)   2024-05-17 22:41:00
大師 等我學完java來摸摸看rust
作者: yam276 ('_')   2024-05-17 22:42:00
你要先學Pointer 不然會不懂為啥搞這麼麻煩但這語言的借用在你寫code的時候就是個糞坑
作者: DJYOSHITAKA (Evans)   2024-05-17 22:42:00
看不懂捏= =
作者: sustainer123 (caster)   2024-05-17 22:43:00
我學過一年C 雖然一段時間沒寫惹
作者: yam276 ('_')   2024-05-17 22:43:00
Option=Some跟None 就是避免nullptrRc=智慧指標 RefCell=容器obj=類別名RefCell會強制檢查後面obj的借用 避免C++的狗屎問題但他這一套組合拳下來把自己也變狗屎了

Links booklink

Contact Us: admin [ a t ] ucptt.com