題目描述:
給定一個二叉搜尋樹, 找到該樹中兩個指定節點的最近公共祖先。
百度百科中最近公共祖先的定義為:“對于有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個節點也可以是它自己的祖先)。”
例如,給定如下二叉搜尋樹: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
輸出: 6
解釋: 節點 2 和節點 8 的最近公共祖先是 6。
示例 2:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
輸出: 2
解釋: 節點 2 和節點 4 的最近公共祖先是 2, 因為根據定義最近公共祖先節點可以為節點本身。
說明:
所有節點的值都是唯一的。
p、q 為不同節點且均存在于給定的二叉搜尋樹中。
此題思路:題目給出一個二叉搜尋樹,需要我們找到p和q的最近公共祖先,那麼我們就一定要找到他們最開始的分割點,這個分割點就是我們要找的節點。那麼這個問題就可以分幾種情況讨論
1、p和q都在目前節點的右子樹上,則周遊右子樹
2、p和q都在目前節點的左子樹上,則周遊左子樹
3、如果上述兩種情況都不滿足,則說明找到了最近的公共分割點
/**
* 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(root==NULL)
return NULL;
//周遊二叉搜尋樹
int num1=p->val,num2=q->val;
//兩個節點都在右子樹上,周遊右子樹
if(num1>root->val&&num2>root->val){
return lowestCommonAncestor(root->right,p,q);
}
//兩個節點都在左子樹上,周遊左子樹
if(num1<root->val&&num2<root->val){
return lowestCommonAncestor(root->left,p,q);
}
else
return root;
}
};
時間複雜度:O(n),周遊樹所消耗的時間=樹節點個數*通路每個節點所消耗的時間。
/**
* 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;
// Value of q;
int qVal = q->val;
// Start from the root node of the tree
TreeNode* node = root;//聲明樹指針
// Traverse the tree
while (node != NULL) {
// Value of ancestor/parent node.
int parentVal = node->val;
if (pVal > parentVal && qVal > parentVal) {
// If both p and q are greater than parent
node = node->right;
} else if (pVal < parentVal && qVal < parentVal) {
// If both p and q are lesser than parent
node = node->left;
} else {
// We have found the split point, i.e. the LCA node.
return node;
}
}
return NULL;
}
};