您的位置:首页 > 编程语言 > Java开发

[Java]寻找最低公共祖先(普通树的情形)Lowest Common Ancestor of a Binary Tree

2015-08-15 22:06 525 查看
leetcode 原题链接 https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined
between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______
/              \
___5__          ___1__
/      \        /      \
6      _2       0       8
/  \
7   4


For example, the lowest common ancestor (LCA) of nodes 
5
 and 
1
 is 
3
.
Another example is LCA of nodes 
5
 and 
4
 is 
5
,
since a node can be a descendant of itself according to the LCA definition.
简要翻译:
这道题也是求公共祖先问题,但是这是普通树情形,而我的上一篇博客是二叉树情形,相当于是其通用解法。

简要分析:

这里是一个普通树,我们依然可以借助三种常用遍历方式中的一种来分别求得两个给定节点到根节点的路径,然后计算这两条路径第一个相交节点即可。

在实现过程中,我们需要两个stack来分别存储两个节点的路径。

实现代码如下:

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
Stack<TreeNode> stackp = new Stack<TreeNode>();
Stack<TreeNode> stackq = new Stack<TreeNode>();
getPath(root, p, stackp);
getPath(root, q, stackq);
return lowestCommonAncestor(stackp, stackq);
}
private TreeNode lowestCommonAncestor(Stack<TreeNode> stackp, Stack<TreeNode> stackq)
{
TreeNode target = null;
while (!stackp.isEmpty() && !stackq.isEmpty() && stackp.peek() == stackq.peek())
{
target = stackp.peek();
stackp.pop();
stackq.pop();
}
return target;
}
private boolean getPath(TreeNode root, TreeNode p, Stack<TreeNode> stackp)
{
// TODO Auto-generated method stub
if (root == null)
return false;
if (root == p)
{
stackp.push(root);
return true;
}
else
{
if (getPath(root.left, p, stackp) || getPath(root.right, p, stackp))
{
stackp.push(root);
return true;
}
}
return false;
}


ps:需要说明的是,这个代码在实现过程中,是当找到给定节点的时候才将路径依次压入stack中的,也就是说,两个stack的栈顶都是存放着root节点。因此,此时就应该找两条路径分离开之前的最后一个节点,此节点就是所求的最低公共祖先。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java 二叉树