二叉搜索树的最近公共祖先I——leetcode68

二叉搜索树的最近公共祖先I

题目:二叉搜索树的最近公共祖先

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

示例:

输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6 
解释: 节点 2 和节点 8 的最近公共祖先是 6。

题解

方法1:分支法

1. 根节点左节点为null,右节点不为null,返回右节点

2.根节点右节点为null,左节点不为null,返回左节点

3.根节点左右节点均不为null,返回根节点

 

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

方法2:并查集

class Solution0 {
    Map<TreeNode, TreeNode> map;
    Set<TreeNode> set;

    public void dfs(TreeNode father, TreeNode p) {
        if (p == null) return;
        map.put(p, father);
        dfs(p, p.left);
        dfs(p, p.right);
    }

    public void up(TreeNode p)
    {
        set.add(p);
        if(map.get(p)==p) return;
        up(map.get(p));
    }

    public TreeNode dfs2(TreeNode q)
    {
        if(set.contains(q))
            return q;
        return dfs2(map.get(q));
    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        map = new HashMap<>();
        set=new HashSet<>();
        dfs(root, root);
        up(p);
        return dfs2(q);
    }
}
posted @ 2022-01-02 18:48  言思宁  阅读(23)  评论(0编辑  收藏  举报