530.二叉搜索树的最小绝对差
题目链接:530.二叉搜索树的最小绝对差
思路:中序遍历,用pre节点记录cur节点的前一个节点的值。
class Solution {
int result = Integer.MAX_VALUE;
TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
traversal(root);
return result;
}
private void traversal(TreeNode cur){
if(cur == null)return;
traversal(cur.left);
if(pre!=null){
result = Math.min(result,cur.val-pre.val);
}
pre = cur;
traversal(cur.right);
}
}
501.二叉搜索树中的众数
题目链接:501.二叉搜索树中的众数
思路:遍历元素出现频率可以将相邻两个元素进行比较,输出出现频率最高的元素。用count存储当前元素出现频率,maxCount存储最大频率,二者进行比较。当count>maxCount的时候,更新maxCount并清空结果集result。
class Solution {
TreeNode pre = null;
int count = 0;
int maxCount = 0;
ArrayList<Integer> result;
public int[] findMode(TreeNode root) {
result = new ArrayList<>();
traversal(root);
int[] res = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
res[i] = result.get(i);
}
return res;
}
public void traversal(TreeNode cur){
if(cur == null)return;
traversal(cur.left);
if(pre == null){
count = 1;
}else if(pre.val == cur.val){
count++;
}else{
count = 1;
}
pre = cur;
if(count == maxCount)result.add(cur.val);
if(count > maxCount){
maxCount = count;
result.clear();
result.add(cur.val);
}
traversal(cur.right);
}
}
236. 二叉树的最近公共祖先
题目链接:236. 二叉树的最近公共祖先
思路:遍历过程中遇到p或q返回,对左子树和右子树进行递归操作。左与右的处理逻辑:左右都不为空返回根节点,左为空右不为空返回右节点,左不为空右为空返回左节点。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)return root;
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 right;
}else if(left!=null&&right==null){
return left;
}
else{
return null;
}
}
}