首页 > 其他 > 详细

Lowest Common Ancestor of a Binary Search Tree

时间:2014-03-18 11:54:40      阅读:302      评论:0      收藏:0      [点我收藏+]

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

 

4种情况。

  1. Both nodes are to the left of the tree.
  2. Both nodes are to the right of the tree.
  3. One node is on the left while the other is on the right.
  4. When the current node equals to either of the two nodes, this node must be the LCA too.
bubuko.com,布布扣
1 Node *LCA(Node *root, Node *p, Node *q) {
2   if (!root || !p || !q) return NULL;
3   if (max(p->data, q->data) < root->data)
4     return LCA(root->left, p, q);
5   else if (min(p->data, q->data) > root->data)
6     return LCA(root->right, p, q);
7   else
8     return root;
9 }
bubuko.com,布布扣

 

http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-search-tree.html

Lowest Common Ancestor of a Binary Search Tree,布布扣,bubuko.com

Lowest Common Ancestor of a Binary Search Tree

原文:http://www.cnblogs.com/longhorn/p/3606704.html

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