一、938二叉搜索树的范围和
1.题目
https://leetcode-cn.com/problems/range-sum-of-bst/
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
2.思路
1.深度优先搜索(可套用二叉树的前序遍历)
2.可利用二叉搜索(查找)树的特性:左子树<根节点<右子树
3.代码
1.二叉树前序遍历
/**
* 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 int rangeSumBST(TreeNode root, int low, int high) {
//题目的意思是返回值在[L,H]区间的值的总和,即L<=X<=H
int res = 0;
if (root == null) return res;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
//stack.add(cur);//如果root满足条件的话,会多加一次,注意取消
while(cur!=null || !stack.isEmpty()){
while (cur!=null){
if(cur.val >=low && cur.val <= high){
res += cur.val;
}
stack.add(cur);
cur = cur.left;
}
cur = stack.pop();
cur = cur.right;
}
return res;
}
}
2.官方题解
/**
* 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 int rangeSumBST(TreeNode root, int low, int high) {
//题目的意思是返回值在[L,H]区间的值的总和,即L<=X<=H
if (root == null) return 0;
if (root.val <low) return rangeSumBST(root.right,low,high);
if(root.val > high) return rangeSumBST(root.left,low,high);
return root.val+rangeSumBST(root.left,low,high)+rangeSumBST(root.right,low,high);
}
}
二、78子集
可参考回溯:https://blog.csdn.net/Xiao__Bei/article/details/121754875
三、200岛屿数量
1.题目
https://leetcode-cn.com/problems/number-of-islands/
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
2.思路
可参考官网题解里大神的解题思路
https://leetcode-cn.com/problems/number-of-islands/solution/dao-yu-lei-wen-ti-de-tong-yong-jie-fa-dfs-bian-li-/
3.代码
class Solution {
public void dfs(char[][] grid, int c, int r){
//base case
if (c<0||c>=grid.length||r<0||r>=grid[0].length){
return;
}
if(grid[c][r] !='1') return;
grid[c][r] = '2';
dfs(grid,c-1,r);
dfs(grid,c+1,r);
dfs(grid,c,r-1);
dfs(grid,c, r+1);
}
public int numIslands(char[][] grid) {
int isLand = 0;
for(int i =0; i<grid.length;i++){
for(int j =0; j<grid[0].length;j++){
if(grid[i][j] == '1'){
isLand++;
dfs(grid,i,j);
}
}
}
return isLand;
}
}