二叉搜尋樹兩結點最低公用祖先結點

來源:互聯網
上載者:User
題目

給定一棵二叉搜尋樹(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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.