530.二叉搜索树的最小绝对差
/**
* 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 {
//双指针法
TreeNode pre = null;
int result = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if(root == null) return 0;
generateResult(root);
return result;
}
public void generateResult(TreeNode root){
if(root == null) return;
generateResult(root.left);
if(pre !=null){
result = Math.min(result,root.val-pre.val);
}
pre = root;
generateResult(root.right);
}
}
501.二叉搜索树中的众数
/**
* 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 {
int count = 0;//定义频率;
int maxCount = 0;//定义最大频率
List<Integer> resultList = new ArrayList<>();
TreeNode pre = null;
public int[] findMode(TreeNode root) {
doGenerateResult(root);
int[] res = new int[resultList.size()];
for(int i = 0;i<res.length;i++){
res[i] = resultList.get(i);
}
return res;
}
public void doGenerateResult(TreeNode root){
if(root == null) return;
doGenerateResult(root.left);
int val = root.val;
if(pre == null || pre.val != root.val){
count = 1;
}else{
count ++;
}
if(count > maxCount){
maxCount = count;
resultList.clear();
resultList.add(val);
}else if(count == maxCount){
resultList.add(val);
}
pre = root;
doGenerateResult(root.right);
}
}
- 二叉树的最近公共祖先
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
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 left;
}else if(left == null && right != null){
// //从右节点返回
return right;
}else{
//左右节点满足
return root;
}
}
}