235. 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.
思路:
mine思路:
1.將各個節點的從root到節點的路徑都記錄下來vector<vector<int>>,vector中最后一個元素為當前節點。
2.找到目標的兩個vector,比較之找到較短的"根"
others思路:
在二叉查找樹種,尋找兩個節點的最低公共祖先。
1、如果a、b都比根節點小,則在左子樹中遞歸查找公共節點。
2、如果a、b都比根節點大,則在右子樹中查找公共祖先節點。
3、如果a、b一個比根節點大,一個比根節點小,或者有一個等于根節點,則根節點即為最低公共祖先。
代碼如下:(代碼實現為others思路)
/**
* 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) {
int pVal = p->val;
int qVal = q->val;
int rootVal = root->val;
if(pVal < rootVal && qVal < rootVal)
{
return lowestCommonAncestor(root->left,p,q);
}
else if(pVal > rootVal && qVal > rootVal)
{
return lowestCommonAncestor(root->right,p,q);
}
return root;
}
};2016-08-07 09:47:25
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。