Lintcode88 Lowest Common Ancestor solution 题解

来源:互联网 发布:淘宝开店宝贝照片拍摄 编辑:程序博客网 时间:2024/06/06 06:46

【题目描述】

Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.

给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。

最近公共祖先是两个节点的公共的祖先节点且具有最大深度。

【注】假设给出的两个节点都在树中存在

【题目链接】

www.lintcode.com/en/problem/lowest-common-ancestor/

【题目解析】

可以用递归来解决,递归寻找两个带查询LCA的节点p和q,当找到后,返回给它们的父亲。如果某个节点的左右子树分别包括这两个节点,那么这个节点必然是所求的解,返回该节点。否则,返回左或者右子树(哪个包含p或者q的就返回哪个)。

【参考答案】

www.jiuzhang.com/solutions/lowest-common-ancestor/


原创粉丝点击