楼主:
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)
}
}