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

[LeetCode] Lowest Common Ancestor of a Binary Search Tree

时间:2015-07-11 15:02:07      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

Well, remember to take advantage of the property of binary search trees, which is, root -> left -> val < root -> val < root -> right -> val. Moreover, both p and q will be the descendants of the root of the subtree that contains both of them. And the root with the largest depth is just the lowest common ancestor. This idea can be turned into the following simple recursive code.

 1 class Solution {
 2 public:
 3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
 4         if (p -> val < root -> val && q -> val < root -> val)
 5             return lowestCommonAncestor(root -> left, p, q);
 6         if (p -> val > root -> val && q -> val > root -> val)
 7             return lowestCommonAncestor(root -> right, p, q);
 8         return root;
 9     }
10 };

This code is really short, right? If you still want to shorten it, this link provide nice alternatives. 

[LeetCode] Lowest Common Ancestor of a Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4638519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!