1325. Delete Leaves With a Given Value Medium

@problem@discussion
#Tree#Depth-First Search#Binary Tree



1/**
2 * [1325] Delete Leaves With a Given Value
3 *
4 * Given a binary tree root and an integer target, delete all the leaf nodes with value target.
5 * Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).
6 *  
7 * Example 1:
8 * <img alt="" src="https://assets.leetcode.com/uploads/2020/01/09/sample_1_1684.png" style="width: 500px; height: 112px;" />
9 * 
10 * Input: root = [1,2,3,2,null,2,4], target = 2
11 * Output: [1,null,3,null,4]
12 * Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). 
13 * After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).
14 * 
15 * Example 2:
16 * <img alt="" src="https://assets.leetcode.com/uploads/2020/01/09/sample_2_1684.png" style="width: 400px; height: 154px;" />
17 * 
18 * Input: root = [1,3,3,3,2], target = 3
19 * Output: [1,3,null,null,2]
20 * 
21 * Example 3:
22 * <img alt="" src="https://assets.leetcode.com/uploads/2020/01/15/sample_3_1684.png" style="width: 500px; height: 166px;" />
23 * 
24 * Input: root = [1,2,null,2,null,2], target = 2
25 * Output: [1]
26 * Explanation: Leaf nodes in green with value (target = 2) are removed at each step.
27 * 
28 *  
29 * Constraints:
30 * 
31 * 	The number of nodes in the tree is in the range [1, 3000].
32 * 	1 <= Node.val, target <= 1000
33 * 
34 */
35pub struct Solution {}
36use crate::util::tree::{TreeNode, to_tree};
37
38// problem: https://leetcode.com/problems/delete-leaves-with-a-given-value/
39// discuss: https://leetcode.com/problems/delete-leaves-with-a-given-value/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43// Definition for a binary tree node.
44// #[derive(Debug, PartialEq, Eq)]
45// pub struct TreeNode {
46//   pub val: i32,
47//   pub left: Option<Rc<RefCell<TreeNode>>>,
48//   pub right: Option<Rc<RefCell<TreeNode>>>,
49// }
50// 
51// impl TreeNode {
52//   #[inline]
53//   pub fn new(val: i32) -> Self {
54//     TreeNode {
55//       val,
56//       left: None,
57//       right: None
58//     }
59//   }
60// }
61use std::rc::Rc;
62use std::cell::RefCell;
63impl Solution {
64    pub fn remove_leaf_nodes(root: Option<Rc<RefCell<TreeNode>>>, target: i32) -> Option<Rc<RefCell<TreeNode>>> {
65        Some(Rc::new(RefCell::new(TreeNode::new(0))))
66    }
67}
68
69// submission codes end
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn test_1325() {
77    }
78}
79


Back
© 2025 bowen.ge All Rights Reserved.