Leecode brush title
- Title Description
Given a binary search tree, find the nearest common ancestor of the two specified nodes of the tree.
Baidu Encyclopedia recent common ancestor as defined: "For two nodes of the root of the tree T p, q, is represented as a common ancestor node x, that x is p, q ancestor depth as large as possible and x (a node can be its own ancestors). "
- Example
For example, given the following binary search tree: root = [6,2,8,0,4,7,9, null, null, 3,5]
Input: root = [6,2,8,0,4,7,9, null, null, 3,5], p = 2, q = 8
Output: 6
Explanation: nodes 2 and 8 is the common ancestor 6.
Input: root = [6,2,8,0,4,7,9, null, null, 3,5], p = 2, q = 4
Output: 2
Explanation: nodes 2 and 4 are common ancestor 2, because by definition a recent common ancestor node can be a node itself.
- Code
//注意利用搜索二叉树的特性即可
/**
* 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;
if(p->val>=root->val&&q->val<=root->val||p->val<=root->val&&q->val>=root->val)
{
return root;
}
else if(p->val>=root->val)
{
TreeNode* node;
node = lowestCommonAncestor(root->right,p,q);
return node;
}
else if(p->val<=root->val)
{
TreeNode* node;
node = lowestCommonAncestor(root->left,p,q);
return node;
}
else
return NULL;
}
};