使用分治的方式,使用深度优先遍历
/**
* @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;
}
}
本文介绍了如何使用分治方法结合深度优先搜索算法来解决一个问题,即在给定一棵树中找到一个节点值之和不超过限制的子树。通过递归实现,着重展示了如何从叶子节点开始,逐步缩小范围并返回合适的子树结构。
616

被折叠的 条评论
为什么被折叠?



