使用分治的方式,使用深度优先遍历
/**
* @author xnl
* @Description:
* @date: 2022/6/5 23:23
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
public TreeNode sufficientSubset(TreeNode root, int limit) {
if (root == null){
return null;
}
// 叶子节点
if (root.left == null && root.right == null){
if (root.val < limit){
return null;
}
return root;
}
root.left = sufficientSubset(root.left, limit - root.val);
root.right = sufficientSubset(root.right, limit - root.val);
return root.left == null && root.right == null ? null : root;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}