501 二叉搜索树中的众数
给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树
思路:dfs遍历二叉搜索树,利用hashmap存储每个节点出现的次数,最后通过value进行降序排序,输出
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<Integer,Integer> hashmap = new HashMap();
public int[] findMode(TreeNode root) {
int[] res = new int[1];
dfs(root);
List<Map.Entry<Integer,Integer>> list = new ArrayList(hashmap.entrySet());
Collections.sort(list,(o1,o2)->o2.getValue().compareTo(o1.getValue()));
res[0] = list.get(0).getKey();
int number = list.get(0).getValue();
int k=1;
for(int i=1;i<list.size();i++){
if(list.get(i).getValue()==number){
res = Arrays.copyOf(res,res.length+1);
res[k++] = list.get(i).getKey();
}else{
break;
}
}
return res;
}
public void dfs(TreeNode root){
if(root==null) return;
dfs(root.left);
hashmap.put(root.val,hashmap.getOrDefault(root.val,0)+1);
dfs(root.right);
}
}
236 二叉树的最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
思路:对二叉树进行递归,当root为null、p、q这三种情况的时候,进行返回,若没有返回,若root不为null、p、q,则判断root的左右子树left和right的返回值,若left和right都不为空,则代表都有返回值,为p或q,直接返回root即可;若left或right有一方为空,直接返回另一方即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
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) return right;
if(right==null) return left;
return root;
}
}