LeetCode Everyday -- 253
進入正題之前先扯些廢話。以下可以跳過。
現在大三了,馬上就要畢業找工作了。暮然回首,發現這三年除了學了一些在外行人面前裝逼的詞彙外並沒有學到什麼太多東西。上課也是水水的求個及格,渾渾噩噩過了三年。在大學最後這一年裡,希望能過重新學點東西,不至於荒廢四年。
我們程式設計師外修語言內修演算法。所以,我決定重新開始學習演算法。在知乎上逛了一圈,決定從刷leetcode開始。
leetcode上題目分easy,medium,hard三個水平,每個題目會統計出ac率,所以,作為演算法菜鳥,將easy的題目篩選出來,從ac最高的開始,進入演算法的學習之路。
由於水平有限,難免出現差錯,希望各位大神能過指正。
好了,廢話說完了,進入正題。
Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if( p->val < root->val && q->val < root->val){
return lowestCommonAncestor(root->left,p,q);
}else if(p->val > root->val && q->val > root -> val ){
return lowestCommonAncestor(root->right,p,q);
}
return root;
}
};
leetcode上支援多種語言提交,包括C,C++,java,python,js等,未來提高演算法效率,我選擇的是C/C++語言。從leetcode統計的資料來看,C,C++普遍比其他語言快。
解題思路:
題目的關鍵是BST,BST(二叉搜尋樹)學過資料結構的人都應該知道,它一個重要的特點就是樹的左邊<根節點<左邊,所以,要找到兩個節點的公共祖先,關鍵就是找到一個節點讓兩個節點分佈在它的兩側。因為要找最近公共祖先,所以從根節點開始一層層往下找,找到的第一個節點即為最近根節點。