538二叉搜索树转换为累加树
递归:使用pronode标记仅小于该节点的节点,使用右中左的顺序 根据pronode值修改节点值
class Solution {
TreeNode pronode = null;
public TreeNode convertBST(TreeNode root) {
if (root==null){
return root;
}
if (root.right!=null){
convertBST(root.right);
}
if (pronode!=null){
root.val += pronode.val;
}
pronode = root;
if (root.left!=null){
convertBST(root.left);
}
return root;
}
}
77组合
回溯法
class Solution {
List<List<Integer>> result= new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}
public void backtracking(int n,int k,int startIndex){
if (path.size() == k){
result.add(new ArrayList<>(path));
return;
}
for (int i =startIndex;i<=n;i++){
path.add(i);
backtracking(n,k,i+1);
path.removeLast();
}
}
}
收获
组合问题可以转化成树从而更容易理解
树问题和回溯密不可分