代码随想录day21
530.二叉搜索树的最小绝对差
class Solution {
TreeNode pre;
int result = Integer . MAX_VALUE ;
public int getMinimumDifference ( TreeNode root) {
if ( root== null ) return 0 ;
traversal ( root) ;
return result;
}
public void traversal ( TreeNode root) {
if ( root== null ) return ;
traversal ( root. left) ;
if ( pre!= null ) {
result = Math . min ( result, root. val- pre. val) ;
}
pre = root;
traversal ( root. right) ;
}
}
501.二叉搜索树中的众数
class Solution {
HashMap < Integer , Integer > keyToFreq = new HashMap < > ( ) ;
HashMap < Integer , LinkedHashSet < Integer > > freqToKey = new HashMap < > ( ) ;
int maxFreq = 0 ;
public int [ ] findMode ( TreeNode root) {
recursion ( root) ;
return freqToKey. get ( maxFreq) . stream ( ) . mapToInt ( x -> x) . toArray ( ) ;
}
private void recursion ( TreeNode root) {
if ( root == null ) {
return ;
}
recursion ( root. left) ;
keyToFreq. put ( root. val, keyToFreq. getOrDefault ( root. val, 0 ) + 1 ) ;
int key = root. val;
int freq = keyToFreq. get ( root. val) ;
maxFreq = Math . max ( freq, maxFreq) ;
freqToKey. putIfAbsent ( freq, new LinkedHashSet < Integer > ( ) ) ;
freqToKey. get ( freq) . add ( key) ;
recursion ( root. right) ;
}
}
236.二叉树的最近公共祖先
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 null ;
if ( left == null ) return right;
if ( right == null ) return left;
return root;
}
}