代码随想录算法训练营第21天|530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数 、236.二叉树的最近公共祖先
一. 二叉树相关算法题
530.二叉搜索树的最小绝对差
递归
思路
根据据二叉搜索树中序遍历的顺序性最小绝对差一定是相邻的两个节点
class Solution {
int min = Integer . MAX_VALUE;
TreeNode pre = null ;
public int getMinimumDifference ( TreeNode root) {
if ( root == null ) return - 1 ;
getMinimumDifference ( root. left) ;
if ( pre != null ) {
int sub = Math . abs ( root. val- pre. val) ;
min = Math . min ( min, sub) ;
}
pre = root;
getMinimumDifference ( root. right) ;
return min;
}
}
501.二叉搜索树中的众数
递归
思路
针对普通二叉树查找众数的逻辑
递归遍历二叉树将节点value与出现次数放入map中 针对出现次数排序 返回次数最大的节点
class Solution {
Map < Integer , Integer > map = new HashMap < > ( ) ;
public int [ ] findMode ( TreeNode root) {
getMap ( root) ;
List < Map. Entry < Integer , Integer > > entryList = map. entrySet ( ) . stream ( )
. sorted ( ( c1, c2) -> c2. getValue ( ) . compareTo ( c1. getValue ( ) ) )
. collect ( Collectors . toList ( ) ) ;
List < Integer > resList = new ArrayList < > ( ) ;
resList. add ( entryList. get ( 0 ) . getKey ( ) ) ;
for ( int i = 1 ; i < entryList. size ( ) ; i++ ) {
if ( entryList. get ( i) . getValue ( ) == entryList. get ( 0 ) . getValue ( ) ) {
resList. add ( entryList. get ( i) . getKey ( ) ) ;
}
}
return resList. stream ( ) . mapToInt ( Integer :: intValue ) . toArray ( ) ;
}
public void getMap ( TreeNode root) {
if ( root == null ) return ;
map. put ( root. val, map. getOrDefault ( root. val, 0 ) + 1 ) ;
getMap ( root. left) ;
getMap ( root. right) ;
}
}
针对本题是二叉搜索树,根据二叉搜索树的特性使用中序遍历的话,二叉树是顺序递增的,相同节点指定相邻,可以使用双指针判断
class Solution {
int maxCount = 0 ;
int count = 0 ;
TreeNode pre = null ;
List < Integer > res = new ArrayList < > ( ) ;
public int [ ] findMode ( TreeNode root) {
searceBST ( root) ;
return res. stream ( ) . mapToInt ( Integer :: intValue ) . toArray ( ) ;
}
public void searceBST ( TreeNode root) {
if ( root == null ) return ;
searceBST ( root. left) ;
if ( pre == null ) {
count = 1 ;
} else if ( pre. val== root. val) {
count++ ;
} else {
count = 1 ;
}
pre = root;
if ( count == maxCount) {
res. add ( root. val) ;
}
if ( count> maxCount) {
res. clear ( ) ;
res. add ( root. val) ;
maxCount = count;
}
searceBST ( root. right) ;
}
}
236.二叉树的最近公共祖先
思路
寻找公共祖先要从下向上遍历那么就要使用后序递归遍历了:
查找是否有个节点的左右子树能够分别找到p和q,如果找到返回当前节点 如果只找到一个则返回这一个并向上回溯 针对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 right;
else if ( left != null && right == null ) return left;
else return null ;
}
}