作者yam276 (史萊哲林的優等生)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Fri May 17 22:38:30 2024
※ 引述《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)
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.249.242 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715956712.A.E2F.html
推 steven183: 別卷了 05/17 22:38
→ yam276: 好討厭Option<Rc<RefCell<obj>>> 05/17 22:39
→ aioiwer318: 別卷了 05/17 22:39
推 sustainer123: 大師 等我學完java來摸摸看rust 05/17 22:41
→ yam276: 你要先學Pointer 不然會不懂為啥搞這麼麻煩 05/17 22:42
→ yam276: 但這語言的借用在你寫code的時候就是個糞坑 05/17 22:42
推 DJYOSHITAKA: 看不懂捏= = 05/17 22:42
→ sustainer123: 我學過一年C 雖然一段時間沒寫惹 05/17 22:43
→ yam276: Option=Some跟None 就是避免nullptr 05/17 22:43
→ yam276: Rc=智慧指標 RefCell=容器 05/17 22:43
→ yam276: obj=類別名 05/17 22:44
→ yam276: RefCell會強制檢查後面obj的借用 避免C++的狗屎問題 05/17 22:44
→ yam276: 但他這一套組合拳下來把自己也變狗屎了 05/17 22:44