236.二叉树的最近公共祖先

image-20200510160921799


官方题解:

https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/er-cha-shu-de-zui-jin-gong-gong-zu-xian-by-leetc-2/

哈希表记录节点的父节点

思路

  • 该思路比较好理解

  • 从根节点开始遍历整棵二叉树,用哈希表记录每个节点的父节点指针。

  • 从 p 节点开始不断往它的祖先移动,并用数据结构记录已经访问过的祖先节点。

  • 同样,我们再从 q 节点开始不断往它的祖先移动,如果有祖先已经被访问过,即意味着这是 p 和 q 的深度最深的公共祖先,即 LCA 节点。

代码

    //map记录每个节点的父节点
    Map<Integer,TreeNode> parent=new HashMap<>();
    //Set集合记录以访问过的祖先节点
    Set<Integer> visited=new HashSet<>();

    //遍历整棵二叉树,用哈希表记录每个节点的父节点
    public void dfs(TreeNode root){
        if(root.left!=null){
            parent.put(root.left.val, root);
            dfs(root.left);
        }
        if(root.right!=null){
            parent.put(root.right.val, root);
            dfs(root.right);
        }
    }

    /*
     * 12ms  31%
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);
        while(p!=null){
            visited.add(p.val);
            p=parent.get(p.val);
        }
        while(q!=null){
            if(visited.contains(q.val)){
                return q;
            }
            q=parent.get(q.val);
        }
        return  null;
    }

递归

思路

后序遍历dfs

作者:Krahets

仰望大佬。。。

原文地址:https://www.cnblogs.com/yh-simon/p/12864063.html