113.路径总和II(回溯)
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Deque<Integer> path = new ArrayDeque<>();
dfs(root, targetSum, path, res);
return res;
}
public void dfs(TreeNode root, int targetSum, Deque<Integer> path, List<List<Integer>> res) {
if(root == null) return;
if(root.left == null && root.right == null) {
if(targetSum == root.val) {
path.addLast(root.val);
res.add(new ArrayList<>(path));
path.removeLast();
}
return;
}
path.addLast(root.val);
dfs(root.left, targetSum - root.val, path, res);
dfs(root.right, targetSum = root.right, path, res);
path.removeLast();
}
}
114.二叉树展开为链表(递归)
class Solution {
public void flatten(TreeNode root) {
if(root == null) return;
flatten(root.left);
flatten(root.right);
TreeNode temp = root.right;
root.right = root.left;
root.left = null;
while(root.right != null) root = root.right;
root.right = temp;
}
}