8月算法训练------第五天(搜索与回溯)解题报告
题目类型:搜索与回溯
题目难度:简单
第一题、剑指 Offer 34. 二叉树中和为某一值的路径
-
思路分析:
使用二叉树的深度优先遍历,如果遍历到的值的和与target相等,则这个值组合可以是答案。 -
代码:
class Solution {
List<List<Integer>> ret = new LinkedList();
Deque<Integer> path = new LinkedList();
public List<List<Integer>> pathSum(TreeNode root, int target) {
dfs(root, target);
return ret;
}
public void dfs(TreeNode root, int target){
if(root == null){
return ;
}
path.offerLast(root.val);
target -= root.val;
if(root.left == null && root.right == null && target == 0){
ret.add(new ArrayList<Integer>(path));
}
dfs(root.left, target);
dfs(root.right, target);
path.pollLast();
}
}
第二题、剑指 Offer 36. 二叉搜索树与双向链表
- 题目链接:剑指 Offer 36. 二叉搜索树与双向链表
- 思路分析:
这一题要使用二叉树的中序遍历,因为题目中的二叉树已经是二叉搜索树,所以比根节点小的值在左子树,比根节点大的值在右边,所以要用中序遍历,先将小的值全部遍历出来,对其左右节点进行改变, - 代码:
class Solution {
Node pre, head;
public Node treeToDoublyList(Node root) {
if(root == null) return null;
dfs(root);
head.left = pre;
pre.right = head;
return head;
}
public void dfs(Node cur){
if(cur == null){
return;
}
dfs(cur.left);
if(pre != null) {
pre.right = cur;
}else {
head = cur;
}
cur.left = pre;
pre = cur;
dfs(cur.right);
}
}
第三题、剑指 Offer 54. 二叉搜索树的第k大节点
- 题目链接:剑指 Offer 54. 二叉搜索树的第k大节点
- 思路分析:
将节点的值存入一个ArrayList中,将ArrayList变为一个数组,对数组进行排序;然后返回第k大的值。 - 代码:
class Solution {
List<Integer> list = new ArrayList();
public int kthLargest(TreeNode root, int k) {
dfs(root);
Integer[] a = list.toArray(new Integer[list.size()]);
Arrays.sort(a);
return a[a.length-k];
}
public void dfs(TreeNode root){
if(root == null){
return ;
}
list.add(root.val);
dfs(root.left);
dfs(root.right);
}
}