题目
思路
最开始以为是相邻节点最小差值,结果发现是任意节点最小差值;对二叉树进行遍历(前序),然后将二叉树进行排序后相邻值相减,保留最小差值;看了题解发现对搜索二叉树进行中序遍历就能得到有序的节点值,因此修改遍历顺序,速度提高了;而且题解是用了一个pre去记录前一个节点的值,这样就可以在遍历的过程中计算最小差值;
代码
class Solution {
int minSub;
int pre;
public int getMinimumDifference(TreeNode root) {
// 任意两个节点的最小值 遍历相减
// 排序 中序遍历就是有序的数组 就不需要排序了
// Collections.sort(re);
minSub = Integer.MAX_VALUE;
pre = -1;
dfs(root);
// 遍历并记录相邻两个数的差值
// for(int i = 0; i < re.size() - 1; i++){
// int j = i + 1;
// int tempSub = re.get(j) - re.get(i);
// minSub = minSub < tempSub ? minSub : tempSub;
// }
return minSub;
}
private void dfs(TreeNode root){
if(root == null){
return;
}
dfs(root.left);
if(pre == -1){
pre = root.val;
}else{
minSub = Math.min(minSub, root.val - pre);
pre = root.val;
}
dfs(root.right);
}
// private List<Integer> dfs(TreeNode root, List<Integer> re){
// if(root == null){
// return re;
// }
// if(root.left != null){
// dfs(root.left, re);
// }
// re.add(root.val);
// if(root.right != null){
// dfs(root.right, re);
// }
// return re;
// }
// 得到相邻节点的最小差值
private int getSub(TreeNode root, int re){
if(root == null){
return re;
}
if(root.left != null){
int tempSub = root.val - root.left.val;
re = re < tempSub ? re: tempSub;
}
if(root.right != null){
int tempSub = root.right.val - root.val;
re = re < tempSub ? re: tempSub;
}
re = getSub(root.left, re);
re = getSub(root.right, re);
return re;
}
}
Tips:
1)int类型的最大值 int re = Integer.MAX_VALUE;
2)在类中定义了变量,在方法中就不要再次定义变量,直接使用;
3)链表List的长度是List.size() 不是length
4)排序Array.sort()是对int[] 数组进行排序
5)绝对值Math.abs(a-b)
题目
思路
深度优先遍历,设置一个同样大小的数组来记录每个位置是否被访问过,防止再次访问;看了题解,直接将访问过的陆地变成水,就不需要额外的数组了;
代码
class Solution {
public int numIslands(char[][] grid) {
// 深度优先遍历 并设置一个数组用来标记每个位置是否被访问过 直接将遍历过的地方改为水 下次就不会进行遍历了
if(grid == null || grid.length == 0){
return 0;
}
int m = grid.length;
int n = grid[0].length;
int isLands = 0;
for(int i = 0; i < m; i ++){
for(int j = 0; j < n ; j++){
if(grid[i][j] == '1'){
++isLands;
dfs(grid, i, j);
}
}
}
return isLands;
}
private void dfs(char[][] grid, int i, int j){
// 获得行列的边界值
int nr = grid.length;
int nc = grid[0].length;
if(i < 0 || j < 0 || i >= nr || j >= nc || grid[i][j] == '0'){
return;
}
// 这里需要将遍历过的地方变成水 防止多次遍历
grid[i][j] = '0';
dfs(grid, i-1, j);
dfs(grid, i+1, j);
dfs(grid, i, j-1);
dfs(grid, i, j+1);
}
}
文章讲述了如何利用中序遍历优化二叉搜索树找到任意节点最小的绝对差值,以及使用深度优先遍历解决岛屿数量问题,通过动态标记已访问区域避免重复。
103

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



