113. 路径总和 II

自己做

解:先序遍历
/*** Definition for a binary tree node.* public 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;* }* }*/
class Solution {private List<List<Integer>> res;public void preTravel(TreeNode root, int targetSum, int sum, List<Integer> list){if(root == null)return;// System.out.println(sum + " "+ list);list.add(root.val); if(root.left == null && root.right == null && sum + root.val == targetSum) //抵达叶子结点res.add(new ArrayList<>(list));//往下传递preTravel(root.left, targetSum, sum + root.val, list);preTravel(root.right, targetSum, sum + root.val, list);//回溯list.remove(list.size() - 1);}public List<List<Integer>> pathSum(TreeNode root, int targetSum) {res = new ArrayList<>();if(root == null)return res;preTravel(root, targetSum, 0, new ArrayList<>());return res;}
}

114. 二叉树展开为链表

自己做

解:建立索引再移动
/*** Definition for a binary tree node.* public 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;* }* }*/
class Solution {//建立索引public TreeNode preTravel(TreeNode root){if(root == null)return null;//如果是叶子结点就返回,以便建立索引if(root.left == null && root.right == null)return root;TreeNode left = preTravel(root.left);//建立索引if(left != null && root.right != null)left.right = root.right;//向上传递索引else if(left != null)return left;TreeNode right = preTravel(root.right);//向上传索引if(right != null)return right;return null; //正常情况建立索引并且右子树无索引后返回}//左孩子移到右孩子上public void move(TreeNode root){if(root == null)return;if(root.left != null){root.right = root.left;root.left = null;}move(root.left);move(root.right);}public void flatten(TreeNode root) {preTravel(root);move(root);}
}
