码迷,mamicode.com
首页 > 其他好文 > 详细

Lowest Common Ancestor of a Binary Search Tree

时间:2015-08-30 12:37:50      阅读:129      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!