该题和昨天的验证二叉搜索树方法一样,利用二叉搜索树的特性,通过中序遍历使用二叉树中的双指针计算最小绝对差。
终止条件:遍历到叶子节点
单层处理逻辑:定义一个全局变量min:Integer.MAX_VALUE来记录最小绝对差,使得min一定会被更新。
class Solution {
int res=Integer.MAX_VALUE;
TreeNode p=null;
public int getMinimumDifference(TreeNode root) {
if(root==null){
return 0;
}
getmin(root);
return res;
}
public void getmin(TreeNode node){
//终止条件
if(node==null){
return;
}
//中序遍历
getmin(node.left);
if(p!=null){
int min=Math.abs(p.val-node.val);
if(min<res){
res=min;
}
}
p=node;
getmin(node.right);
}
}
一入迭代深似海,从此通过是路人,条件太复杂了。
重新学习递归解法,这里有两种情况,一种是存在众数,保存出现频次最高的节点值。另一种是没有众数,要把所有的出现过一次的节点值全部返回,这里就有一个代码的技巧,也是我代码写太少,积累不行;
终止条件:遍历到叶子节点
单层处理逻辑:定义一个count和maxcount,当pre指针和cur指针指向的元素值相等时,count自增,然后将count与maxcount进行比较,若是count等于maxcount,则将元素值存起来,若count大于maxcount,则将数组清空,重新存下这个出现频次最高的新数值,因为这是二叉搜索树,中序遍历,所以元素都是递增的,相同元素都是连续出现。
class Solution {
TreeNode pre=null;
int count=0;
int maxcount=0;
List<Integer> arr=new ArrayList();
public int[] findMode(TreeNode root) {
getmode(root);
int[] res=new int[arr.size()];
int index=0;
for(int i:arr){
res[index++]=i;
}
return res;
}
public void getmode(TreeNode node){
//终止条件
if(node==null){
return;
}
getmode(node.left);
if(pre==null){
count=1;
}else if(pre.val==node.val){
count++;
}else{
count=1;
}
pre=node;
if(maxcount==count){
arr.add(node.val);
}else if(maxcount<count){
arr.clear();
arr.add(node.val);
maxcount=count;
}
getmode(node.right);
}
}
这一题没有思路。听完讲解后懂了解法,但是自己想不出
判断节点p和q的最近公共祖先,需要先找到p和q,然后向上遍历找最近的公共祖先。这里使用后序遍历相当于从下往上遍历,将左右子树的结果返回。这里的结果是直接返回找到的p节点或者q节点,若未找到则返回null。
终止条件:若找到p和q后返回到同一节点,则直接返回节点;若找到p和q的其中一个,则将其返回回去,最终p和q一定会返回到同一个节点上去。
单层处理逻辑:后序遍历
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null){
return null;
}
//终止条件
if(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;
}
}
}