二叉树的最近公共祖先

Posted Alice_yufeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树的最近公共祖先相关的知识,希望对你有一定的参考价值。

/**
 * Definition for a binary tree node.
 * public class TreeNode 
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x)  val = x; 
 * 
 */

class Solution 
    Map<Integer, TreeNode> parent = new HashMap<Integer, TreeNode>();
    Set<Integer> visited = new HashSet<Integer>();

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

    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;
    

以上是关于二叉树的最近公共祖先的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode二叉树的最近公共祖先

求二叉树的最近公共祖先(牛客和力扣的返回值不一样)

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

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

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

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