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

简介: ​给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”​

 题目

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

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

解题思路

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

    代码展示

    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;
        }
    }

    image.gif


    目录
    相关文章
    |
    6天前
    二叉树oj题集(LeetCode)
    二叉树oj题集(LeetCode)
    |
    6天前
    |
    算法 Java C语言
    C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
    C++和Java中的随机函数你玩明白了吗?内附LeetCode470.rand7()爆改rand10()巨详细题解,带你打败LeetCode%99选手
    |
    6天前
    |
    存储 Java
    ZigZagging on a Tree二叉树蛇形层次遍历(Java语言)
    ZigZagging on a Tree二叉树蛇形层次遍历(Java语言)
    11 1
    |
    6天前
    |
    Java
    Tree Traversals Again(Java语言)(先序和中序创建二叉树)(遍历树)
    Tree Traversals Again(Java语言)(先序和中序创建二叉树)(遍历树)
    13 4
    |
    6天前
    leetcode代码记录(二叉树的所有路径
    leetcode代码记录(二叉树的所有路径
    12 0
    |
    6天前
    leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
    leetcode代码记录(对称二叉树 中序遍历+回文串 为什么不行
    8 0
    |
    6天前
    leetcode代码记录(二叉树的最小深度
    leetcode代码记录(二叉树的最小深度
    10 0
    |
    6天前
    leetcode代码记录(二叉树的最大深度
    leetcode代码记录(二叉树的最大深度
    9 0
    |
    6天前
    leetcode代码记录(翻转二叉树
    leetcode代码记录(翻转二叉树
    8 0
    |
    6天前
    leetcode代码记录(二叉树的层序遍历
    leetcode代码记录(二叉树的层序遍历
    12 0

    热门文章

    最新文章