530.二叉搜索树的最小绝对差
关键点1:采用双指针法,pre,cur,预设pre,minValue
关键点2:采用中序遍历,每次中遍历时,判断cur与pre节点之间的数值差与minValue的关系
class Solution {
int minValue = Integer.MAX_VALUE;
TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
if(root == null){
return 0;
}
traversal(root);
return minValue;
}
public void traversal(TreeNode cur){
if(cur == null){
return;
}
traversal(cur.left); // 左
if(pre != null ){ // 中
minValue = Math.min(cur.val - pre.val,minValue);
}
pre = cur;
traversal(cur.right); //右
}
}
501.二叉搜索树中的众数
关键点1:采用双指针法,pre,cur,预设pre,maxCount,count
关键点2:采用中序遍历
2-1:每次中遍历时,判断cur与pre是否相等,相等count++;不相等就把count置为1
2-2:判断count与maxCount之间的关系,如果count > maxCount,更新maxCount,清楚结果集里的节点数值,重新添加最新的众数节点数值进去;如果count == maxCount,添加此时的节点数值进去
class Solution {
List<Integer> list = new ArrayList<>();
TreeNode pre = null;
int maxCount = 0;
int count = 0;
public int[] findMode(TreeNode root) {
traversal(root);
int[] res = new int[list.size()] ;
int j = 0;
for(int i: list){
res[j++] = i;
}
return res;
}
public void traversal(TreeNode cur){
if(cur == null){
return;
}
traversal(cur.left);
if(pre == null || pre.val != cur.val){
count = 1;
}else{
count++;
}
if(count > maxCount) {
maxCount = count;
list.clear();
list.add(cur.val);
}else if(count == maxCount) {
list.add(cur.val);
}
pre = cur;
traversal(cur.right);
}
}
236. 二叉树的最近公共祖先
关键点1:采用后序遍历
关键点2:
2-1:root == null,返回root:
2-2:root == p || root == q,返回root
关键点3:确定几个条件
3-1:左结果为空,右结果为空,往上返回null
3-2:左结果不为空,右结果为空,往上返回左结果
3-3:左结果为空,右结果不为空,往上返回右结果
3-4:左结果不为空,右结果不为空,返回root
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null){
return root;
}
if(root == p || root == q){
return root;
}
TreeNode leftNode = lowestCommonAncestor(root.left,p,q);
TreeNode rightNode = lowestCommonAncestor(root.right,p,q);
if(leftNode != null && rightNode != null){
return root;
}else if(leftNode == null && rightNode != null){
return rightNode;
}else if(leftNode != null && rightNode == null){
return leftNode;
}else{
return null;
}
}
}