二叉树最近公共祖先

给定一颗二叉树以及两个节点,查找两个节点最近的公共祖先,有可能公共祖先是两个节点中的其中一个
比如给定D,E两个节点,其最近的公共祖先为B
在这里插入图片描述
非递归方式
层次遍历找到两个节点,遍历过程中,将每个节点以及它的父节点放到Map中存起来,需要使用到队列,Map,Set
1.根节点入队,并且根节点的父节点为null
2.Map中没有两个给定节点层次遍历
3.队列出队节点,该节点如果存在左右节点,将左右节点分别入队,并且将子节点与父节点存入Map
4.循环2
5.两个节点均找到,将其中一个节点的祖先节点放入Set
6.寻找另一个节点的祖先节点,看看是否在Set中,如果存在返回该祖先节点

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        Map<TreeNode, TreeNode> parentMap = new HashMap<>();
        Queue<TreeNode> queue = new LinkedList<>();
        parentMap.put(root, null);
        queue.add(root);
        while (!parentMap.containsKey(p) || !parentMap.containsKey(q)) {
            TreeNode node = queue.poll();
            if (node.left != null) {
                parentMap.put(node.left, node);
                queue.add(node.left);
            }
            if (node.right != null) {
                parentMap.put(node.right, node);
                queue.add(node.right);
            }
        }
        Set<TreeNode> ancestors = new HashSet<>();
        while (p != null) {
            ancestors.add(p);
            p = parentMap.get(p);
        }
        while (!ancestors.contains(q)){
         	q = parentMap.get(q);
        }
        return q;
    }

递归方式
如果left为null表示两个节点在root的右子树,如果right为null表示两个节点在root的左子树,否则的话是root的左右子树上

     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;
    }
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值