Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.
A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.
A leaf is a node with no children.
Example 1:
Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
Output: [1,2,3,4,null,null,7,8,9,null,14]
Example 2:
Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
Output: [5,4,8,11,null,17,4,7,null,null,null,5]
Example 3:
Input: root = [1,2,-3,-5,null,4,null], limit = -1
Output: [1,null,-3,4]
Constraints:
- The number of nodes in the tree is in the range [1, 5000].
- -105 <= Node.val <= 105
- -109 <= limit <= 109
我们将每个 leaf node 作为一个门, 从 root node 到任意一个 leaf node 的 sum, 如果 sum < limit 则表示此门不通, 反之则表示此门可以通过。 任意一个节点只要向下能走到任何一个可以通过的门就可以得到保留, 否则就要移除出当前 tree。递归函数向上返回 None 则表示当前节点向下走没有任何通路, 否则返回当前 node,表示向下至少有一个通路。注意只有 left child node 和只有 right child node 的情况。
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
fn dfs(
root: Option<Rc<RefCell<TreeNode>>>,
limit: i32,
prev: i32,
) -> Option<Rc<RefCell<TreeNode>>> {
if let Some(node) = root {
let val = node.borrow().val;
if node.borrow().left.is_none() && node.borrow().right.is_none() {
if prev + val < limit {
return None;
}
return Some(node);
}
if node.borrow().left.is_none() {
let right = Solution::dfs(node.borrow_mut().right.take(), limit, prev + val);
if right.is_none() {
return None;
}
node.borrow_mut().right = right;
return Some(node);
}
if node.borrow().right.is_none() {
let left = Solution::dfs(node.borrow_mut().left.take(), limit, prev + val);
if left.is_none() {
return None;
}
node.borrow_mut().left = left;
return Some(node);
}
let left = Solution::dfs(node.borrow_mut().left.take(), limit, prev + val);
let right = Solution::dfs(node.borrow_mut().right.take(), limit, prev + val);
if left.is_none() && right.is_none() {
return None;
}
node.borrow_mut().left = left;
node.borrow_mut().right = right;
return Some(node);
}
None
}
pub fn sufficient_subset(
root: Option<Rc<RefCell<TreeNode>>>,
limit: i32,
) -> Option<Rc<RefCell<TreeNode>>> {
Solution::dfs(root, limit, 0)
}
}