530.二叉搜索树的最小绝对差
思路
二叉搜索树,中序遍历就是按序排列(1,2,3)计算两两最小值
代码
/**
* 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 min=Integer.MAX_VALUE;
TreeNode pre=null;
public int getMinimumDifference(TreeNode root) {
if(root==null) return 0;
find(root);
return min;
}
public void find(TreeNode root){
if(root==null) return;
find(root.left);
if(pre!=null){
min=Math.min(min,root.val-pre.val);
}
pre=root;
find(root.right);
}
}
501.二叉搜索树中的众数
思路
一开始想遍历整棵树,维护HashMap。但是二叉搜索树中序遍历是按序排列,所以可以用全局变量count记录,遇到新的元素就count置1,如果计算到count等于目前最大记录maxCount,就加入到结果记录集中,如果大于maxCount,就要把结果记录集清空再加进去
代码
/**
* 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 maxCount=Integer.MIN_VALUE;
int count=0;
List<Integer> resultVal=new ArrayList<>();
public int[] findMode(TreeNode root) {
find(root);
int[] result=new int[resultVal.size()];
for(int i=0;i<resultVal.size();i++){
result[i]=resultVal.get(i);
}
return result;
}
public void find(TreeNode root){
if(root==null) return;
find(root.left);
if(pre==null || root.val!=pre.val){
count=1;
}
if(pre!=null && root.val==pre.val){
count++;
}
if(count==maxCount){
resultVal.add(root.val);
}else if(count>maxCount){
resultVal.clear();
maxCount=count;
resultVal.add(root.val);
}
pre=root;
find(root.right);
}
}
236. 二叉树的最近公共祖先
思路
后序遍历从下往上找,对于当前节点,如果左右都有结果,说明左右都找到了,这个节点就是公共祖先。但是如果左有右空,有两种情况,两个都在左边(即该节点和该节点的左节点就是要找到那两个)或者左找到了右没找到,但是不管是什么情况,继续往上抛,告诉上面得节点左边有找到,上面接收到左的结果,往右找,抛到最上面,也是两种结果,左有右空,这就说明两个都在左,但是一开始就把结果一直往上抛了,所以最近公共祖先没有变动。
代码
/**
* 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 root;
}else if(left!=null && right==null){
return left;
}else if(left==null && right!=null){
return right;
}else{
return null;
}
}
}