您的位置:首页 > 其它

236. Lowest Common Ancestor of a Binary Tree

2016-06-28 22:12 337 查看
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.

随便给定一个二叉树,求两个节点的最近公共祖先。

普通的树不具有BST的性质,但受到BST最近公共祖先问题路径的启发,同样可以用记录路径的方法来处理。

先对P做一边搜索,搜索的过程【递归地】“标记”节点是否在根节点到P的路径上,以后序的方法遍历能够保证子树的“标记”在根节点之前。

标记完毕路径塞入hashmap以后来处理Q,处理的方法和Q类似,依然是搜索标记一遍,由于后序遍历,子树的标记优先于根节点,搜索遇到的第一个hashmap中存在的节点(公共节点)就是最近的公共祖先。

public class Solution {
HashMap<TreeNode, Integer> hashmap;
TreeNode common=null;

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
if(root==null)
return null;
if(p==q)
return q;

hashmap=new HashMap<>();
hashmap.put(root, hashmap.size());
search(root, p);
find(root, q);
return common;
}

private boolean search(TreeNode t,TreeNode target)
{
if(t==null)
return false;

if(search(t.left, target)||search(t.right, target)||t==target)
{
hashmap.put(t, hashmap.size());
return true;
}

return false;
}

private boolean find(TreeNode t,TreeNode target)
{
if(t==null)
return false;

if(find(t.left, target)||find(t.right, target)||t==target)
{
if(common==null&&hashmap.containsKey(t))
common=t;
return true;
}

return false;
}
}


------------------------------------------------------------------------------------------
https://discuss.leetcode.com/topic/18566/my-java-solution-which-is-easy-to-understand
public 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 && right != null)   return root;
return left != null ? left : right;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: