700.二叉搜索树中的搜索
前几天刚对比了下堆和二叉搜索树。堆是上下位置区分大小,二叉搜索树是左右位置区分大小
这道题简单应用了二叉搜索树的查找功能,直接用前序遍历
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root.val ==val) return root;
if (root.val > val && root.left != null ) return searchBST(root.left, val);
if (root.val < val && root.right != null) return searchBST(root.right,val);
return null;
}
}
98.验证二叉搜索树
中序遍历下,输出的二叉搜索树节点的数值是从小到大的有序序列。
class Solution {
List<Integer> res = new ArrayList<>();
public boolean isValidBST(TreeNode root) {
in(root);
for (int i = 1; i < res.size(); i++) if (res.get(i) <= res.get(i-1)) return false;
return true;
}
void in(TreeNode node) {
if (node.left != null) in(node.left);
res.add(node.val);
if (node.right!= null) in(node.right);
}
}
530.二叉搜索树的最小绝对差
跟上一题一样,遇到在二叉搜索树上求数值问题的题目,可以利用中序遍历把二叉搜索树转化为有序数组,再进行分析。
class Solution {
List<Integer> res = new ArrayList<>();
public int getMinimumDifference(TreeNode root) {
in(root);
int ans = 100000;
for (int i = 1; i < res.size(); i++) ans = Math.min(ans,res.get(i)-res.get(i-1));
return ans;
}
void in(TreeNode node) {
if (node.left != null) in(node.left);
res.add(node.val);
if (node.right!= null) in(node.right);
}
}
501.二叉搜索树中的众数
将节点放到map中,找到最大出现次数并按照该值找到众数
res.stream().mapToInt(Integer::intValue).toArray();实现ArrayList转数组
class Solution {
Map<Integer, Integer> count = new HashMap<>();
List<Integer> res = new ArrayList<>();
public int[] findMode(TreeNode root) {
in(root);
int p = 0;
for (int i : count.values()) p = Math.max(p,i);
for (int i : count.keySet()) {
if (count.get(i) == p) res.add(i);
}
return res.stream().mapToInt(Integer::intValue).toArray();
}
void in(TreeNode node) {
if (node.left != null) in(node.left);
count.put(node.val,count.getOrDefault(node.val,0)+1);
if (node.right!= null) in(node.right);
}
}