首页 > 其他 > 详细

Lowest Common Ancestor of a Binary Search Tree

时间:2015-08-30 12:36:19      阅读:205      评论:0      收藏:0      [点我收藏+]

题目:

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. 

 

 1     public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) 
 2     {
 3         TreeNode m = root;
 4         
 5         if(m.val>p.val&&m.val<q.val) return m;
 6         if(m.val>p.val&&m.val>q.val)
 7         {
 8             return lowestCommonAncestor(root.left,p,q);
 9         }
10         if(m.val<p.val&&m.val<q.val)
11         {
12             return lowestCommonAncestor(root.right,p,q);
13         }
14         
15         return root;
16     }

 

reference:http://www.programcreek.com/2014/07/leetcode-lowest-common-ancestor-of-a-binary-search-tree-java/

Lowest Common Ancestor of a Binary Search Tree

原文:http://www.cnblogs.com/hygeia/p/4770500.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!