class Solution {
TreeNode pre;// 记录上一个遍历的结点int result = Integer.MAX_VALUE;
public intgetMinimumDifference(TreeNode root){if(root==null)return0;traversal(root);return result;}
public voidtraversal(TreeNode root){if(root==null)return;//左traversal(root.left);//中if(pre!=null){
result = Math.min(result,root.val-pre.val);}
pre = root;//右traversal(root.right);}}
二、501.二叉搜索树中的众数
class Solution {
public int[]findMode(TreeNode root){
Map<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();if(root == null)return list.stream().mapToInt(Integer::intValue).toArray();// 获得频率 MapsearchBST(root, map);
List<Map.Entry<Integer, Integer>> mapList = map.entrySet().stream().sorted((c1, c2)-> c2.getValue().compareTo(c1.getValue())).collect(Collectors.toList());
list.add(mapList.get(0).getKey());// 把频率最高的加入 listfor(int i =1; i < mapList.size(); i++){if(mapList.get(i).getValue()== mapList.get(i -1).getValue()){
list.add(mapList.get(i).getKey());}else{break;}}return list.stream().mapToInt(Integer::intValue).toArray();}voidsearchBST(TreeNode curr, Map<Integer, Integer> map){if(curr == null)return;
map.put(curr.val, map.getOrDefault(curr.val,0)+1);searchBST(curr.left, map);searchBST(curr.right, map);}}
236. 二叉树的最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){if(root == null || root == p || root == q){// 递归结束条件return root;}// 后序遍历
TreeNode left =lowestCommonAncestor(root.left, p, q);
TreeNode right =lowestCommonAncestor(root.right, p, q);if(left == null && right == null){// 若未找到节点 p 或 qreturn null;}elseif(left == null && right != null){// 若找到一个节点return right;}elseif(left != null && right == null){// 若找到一个节点return left;}else{// 若找到两个节点return root;}}}