您的位置:首页 > 其它

Lowest Common Ancestor of a Binary Search Tree

2015-08-30 11:20 204 查看
题目:

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

Analysis

This problem can be solved by using BST property, i.e., left < parent < right for each node. There are 3 cases to handle.

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
{
TreeNode m = root;

if(m.val>p.val&&m.val<q.val) return m;
if(m.val>p.val&&m.val>q.val)
{
return lowestCommonAncestor(root.left,p,q);
}
if(m.val<p.val&&m.val<q.val)
{
return lowestCommonAncestor(root.right,p,q);
}

return root;
}


reference:http://www.programcreek.com/2014/07/leetcode-lowest-common-ancestor-of-a-binary-search-tree-java/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: