Description:
题目大意:给出两个节点,在二叉搜索树上找到其最近公共祖先。
解题思路:
算法标签:递归
利用二叉搜索树的性质进行查找。
代码:
/*
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
TreeNode* CommonAncestor(TreeNode* root, int p, int q) {
if(root == NULL)
return root;
if(root -> val == p || root -> val == q)
return root;
// 利用二叉搜索树的性质
// 如果节点都在根节点左边
if(p < root -> val && q < root -> val)
return CommonAncestor(root -> left, p, q);
// 如果节点都在根节点右边
else if(p > root -> val && q > root -> val)
return CommonAncestor(root -> right, p, q);
else
return root;
}
int lowestCommonAncestor(TreeNode* root, int p, int q) {
return CommonAncestor(root , p , q) -> val;
}
};