Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Title:
Solution:
- 1) from the root node traversal binary search tree
- 2) If the right child node in the tree pq, places the right child node as a root Repeat step 1
- 3) If the node pq are left subtree, places left child node as a root Repeat step 1
- 4) If the node is not the same pq in a sub-tree, then there will be three cases of the following figure: pq the left and right sub-tree, the current root is the most recent common ancestor; pq in a node as a root, another sub-node, then p or q is at root node is a common ancestor of the
code is as follows:
class Solution {
public:
//解法1:递归版
TreeNode* lowestCommonAncestor_1(TreeNode* root, TreeNode* p, TreeNode* q) {
int parentVal=root->val;//根节点的值
int pVal=p->val,qVal=q->val;//保存节点pq的值
//若pq都在右子树中,则继续在右子树中寻找最近公共祖先
if(pVal>parentVal&&qVal>parentVal)return lowestCommonAncestor(root->right,p,q);
//若pq都在左子树中,则继续在左子树中寻找最近公共祖先
else if(pVal<parentVal&&qVal<parentVal)return lowestCommonAncestor(root->left,p,q);
//若pq位于左右子树中,那么根节点就是它们的最近公共祖先,或者说pq中的一个就为最近共同祖先
else return root;
}
//解法二:迭代版
TreeNode* lowestCommonAncestor_2(TreeNode* root,TreeNode* p,TreeNode* q)
{
int pVal=p->val,qVal=q->val;//保存节点pq的值
TreeNode *node=root;//用指针node来遍历root为根节点的二叉搜索树
while(node!=nullptr)
{
int parentVal=node->val;//根节点的值
if(pVal>parentVal&&qVal>parentVal)node=node->right;//右子树中继续寻找
else if(pVal<parentVal&&qVal<parentVal)node=node->left;//左子树中继续寻找
else return node;
}
return nullptr;
}
};