題目
給定一棵二叉搜尋樹(BST),找出樹中兩個結點的最低公用祖先結點(LCA)。二叉搜尋樹結點定義:
struct node { int data; struct node* left; struct node* right; };
如為一棵BST,結點2和8的LCA是6,結點4和2的LCA是2。注意,與文章二叉樹兩結點的最低公用祖先結點 中不同,這裡已經說明是二叉搜尋樹(BST),所以可以利用BST的性質進行處理更加簡單。
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
答案
有四種情況需要考慮,分別是
1)兩個結點都在樹的左邊
2)兩個結點都在樹的右邊
3)一個結點在樹的左邊,一個結點在樹的右邊
4)當前結點等於這兩個結點中的一個
對於第1種情況,LCA一定在當前結點的左子樹中;同理,第2種情況,LCA一定在當前結點的右子樹中;而對於第3種和第4種情況,當前結點就是LCA。代碼如下,該演算法時間複雜度為O(h),其中h為BST的高度。
struct node *LCA(struct node *root, struct node *p, struct node *q) { if (!root || !p || !q) return NULL; if (max(p->data, q->data) < root->data) //case 1) return LCA(root->left, p, q); else if (min(p->data, q->data) > root->data) //case 2) return LCA(root->right, p, q); else return root; // case 3)and case 4)}
英文原文:http://www.leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-search-tree.html