236. 二叉树的最近公共祖先 --力扣 --JAVA

题目

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:"对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。"

解题思路

  1. 利用Map存储当前节点和对应的子节点;
  2. 利用递归遍历整棵树,将数据存放到Map当中;
  3. 遍历Map获取最近的公共祖先。

代码展示

java 复制代码
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        Map<TreeNode, List<Integer>> data = new HashMap<>();
        dfs(root,data);
        int min = Integer.MAX_VALUE;
        TreeNode ans = null;
        for (TreeNode treeNode : data.keySet()){
            List<Integer> list = data.get(treeNode);
            int size = list.size();
            if(list.contains(p.val) && list.contains(q.val)){
                if(min > size){
                    min = size;
                    ans = treeNode;
                }
            }
        }
        return ans;
    }
    public List<Integer> dfs(TreeNode root, Map<TreeNode, List<Integer>> data){
        if(root == null){
            return new ArrayList<>();
        }
        List<Integer> store = new ArrayList<>();
        store.add(root.val);
        store.addAll(dfs(root.left,data));
        store.addAll(dfs(root.right,data));
        data.putIfAbsent(root, store);
        return store;
    }
}
相关推荐
易只轻松熊3 分钟前
C++(23):容器类<vector>
开发语言·数据结构·c++
小学生的信奥之路10 分钟前
力扣1991:找到数组的中间位置(前缀和)
数据结构·算法·leetcode·前缀和·数组
এ᭄画画的北北16 分钟前
力扣-102.二叉树的层序遍历
数据结构·算法·leetcode
ccLianLian16 分钟前
数据结构·字典树
数据结构·算法
Lu Yao_28 分钟前
用golang实现二叉搜索树(BST)
开发语言·数据结构·golang
JeffersonZU2 小时前
【数据结构】2-3-1单链表的定义
数据结构·链表
JeffersonZU2 小时前
【数据结构】1-4算法的空间复杂度
c语言·数据结构·算法
L_cl2 小时前
【Python 算法零基础 4.排序 ① 选择排序】
数据结构·算法·排序算法
无聊的小坏坏3 小时前
【数据结构】二叉搜索树
数据结构
山北雨夜漫步3 小时前
机器学习 Day18 Support Vector Machine ——最优美的机器学习算法
人工智能·算法·机器学习