我新建的个人博客,欢迎访问:hmilzy.github.io
530.二叉搜索树的最小绝对差
题目链接: 二叉搜索树的最小绝对差
为什么一串数字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class Solution { TreeNode pre; int result = Integer.MAX_VALUE; public int getMinimumDifference(TreeNode root) { travesal(root); return result; } public void travesal(TreeNode root){ if(root == null){ return; } travesal(root.left); if(pre != null){ result = Math.min(result,root.val - pre.val); } pre = root; travesal(root.right); } }
|
501.二叉搜索树中的众数
题目链接: 二叉搜索树中的众数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
class Solution { ArrayList<Integer> resList; int maxCount; int count; TreeNode pre;
public int[] findMode(TreeNode root) { resList = new ArrayList<>(); maxCount = 0; count = 0; pre = null; findMode1(root); int[] res = new int[resList.size()]; for (int i = 0; i < resList.size(); i++) { res[i] = resList.get(i); } return res; }
public void findMode1(TreeNode root) { if (root == null) { return; } findMode1(root.left);
int rootValue = root.val; if (pre == null || rootValue != pre.val) { count = 1; } else { count++; } if (count > maxCount) { resList.clear(); resList.add(rootValue); maxCount = count; } else if (count == maxCount) { resList.add(rootValue); } pre = root;
findMode1(root.right); } }
|
236. 二叉树的最近公共祖先
题目链接: 二叉树的最近公共祖先
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
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) { return null; }else if(left == null && right != null) { return right; }else if(left != null && right == null) { return left; }else { return root; } } }
|