Re: [閒聊] 每日leetcode

看板Marginalman作者 (史萊哲林的優等生)時間1年前 (2024/05/17 22:38), 編輯推噓3(3010)
留言13則, 5人參與, 1年前最新討論串238/1554 (看更多)
※ 引述《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

05/17 22:38, 1年前 , 1F
別卷了
05/17 22:38, 1F

05/17 22:39, 1年前 , 2F
好討厭Option<Rc<RefCell<obj>>>
05/17 22:39, 2F

05/17 22:39, 1年前 , 3F
別卷了
05/17 22:39, 3F

05/17 22:41, 1年前 , 4F
大師 等我學完java來摸摸看rust
05/17 22:41, 4F

05/17 22:42, 1年前 , 5F
你要先學Pointer 不然會不懂為啥搞這麼麻煩
05/17 22:42, 5F

05/17 22:42, 1年前 , 6F
但這語言的借用在你寫code的時候就是個糞坑
05/17 22:42, 6F

05/17 22:42, 1年前 , 7F
看不懂捏= =
05/17 22:42, 7F

05/17 22:43, 1年前 , 8F
我學過一年C 雖然一段時間沒寫惹
05/17 22:43, 8F

05/17 22:43, 1年前 , 9F
Option=Some跟None 就是避免nullptr
05/17 22:43, 9F

05/17 22:43, 1年前 , 10F
Rc=智慧指標 RefCell=容器
05/17 22:43, 10F

05/17 22:44, 1年前 , 11F
obj=類別名
05/17 22:44, 11F

05/17 22:44, 1年前 , 12F
RefCell會強制檢查後面obj的借用 避免C++的狗屎問題
05/17 22:44, 12F

05/17 22:44, 1年前 , 13F
但他這一套組合拳下來把自己也變狗屎了
05/17 22:44, 13F
文章代碼(AID): #1cHsleul (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cHsleul (Marginalman)