Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)(二叉树的最近公共祖先节点(使用父节点))

Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)(二叉树的最近公共祖先节点(使用父节点))

在这里插入图片描述

Input: LCA of 10 and 14
Output:  12
Explanation: 12 is the closest node to both 10 and 14 
which is a ancestor of both the nodes.

Input: LCA of 8 and 14
Output:  8
Explanation: 8 is the closest node to both 8 and 14 
which is a ancestor of both the nodes.

Input: LCA of 10 and 22
Output:  20
Explanation: 20 is the closest node to both 10 and 22 
which is a ancestor of both the nodes.

LCA的定义

一棵有根的树T。两个节点n1和n2之间的最低共同祖先被定义为T中具有n1和n2作为后代的最低节点(允许一个节点是其自身的后代)。
T中n1和n2的LCA是距离根最远的n1和n2的共同祖先。例如,作为确定树中节点对之间距离的过程的一部分,计算最低共同祖先可能是有用的:从n1到n2的距离可以计算为从根到n1的距离,加上从根到n2的距离,减去从根到其最低共同祖先的距离的两倍。

Algorithm:

1.创建一个空哈希表。
2.在哈希表中插入n1及其所有祖先。
3.检查哈希表中是否存在n2或其任何祖先,如果是,则返回第一个现有祖先。

 public ParentTreeNode insert(ParentTreeNode node, int key) {
            /* If the tree is empty, return a new node */
            if (node == null) return new ParentTreeNode(key);
            /* Otherwise, recur down the tree */
            if (key < node.key) {
                node.left = insert(node.left, key);
                node.left.parent = node;
            } else if (key > node.key) {
                node.right = insert(node.right, key);
                node.right.parent = node;
            }
            /* return the (unchanged) node pointer */
            return node;
        }


        public ParentTreeNode lca(ParentTreeNode node1, ParentTreeNode node2) {
            Map<ParentTreeNode, Boolean> ancestors = new HashMap<>();
            while (node1 != null) {
                ancestors.put(node1, true);
                node1 = node1.parent;
            }
            while (node2 != null) {
                if (ancestors.containsKey(node2)) {
                    return node2;
                }
                node2 = node2.parent;
            }
            return null;
        }

Reference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值