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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
找搜索二叉树最近公共祖先与找二叉树最近公共祖先很像,但搜索二叉树特征更明显,我们可以利用该特征加速寻找。具体来说,当要找的两个节点分别位于root两侧,那说明root即为分裂点。当要找的p,q都大于或者小于root,那说明要去root的子树去找。而去子树找p,q又可用同样方式递归解决。
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return root;
if (root->val<p->val&&root->val<q->val) return lowestCommonAncestor(root->right,p,q);
else if (root->val>p->val&&root->val>q->val) return lowestCommonAncestor(root->left,p,q);
else return root;
}
再聊聊普通二叉树如何找最近公共祖先。
假设找6,4的最近公共祖先,从root开始找,root又分别让左右子树去找,root负责汇总左右子树找的结果。左右子树依然会递归下去,那终止条件就是遇到空节点了或者找到某个要找的节点,那么就返回。返回后根节点开始汇总两个子树的结果,如果两颗子树都找到了,说明该root节点就是最近公共节点;若果左右子树有一棵树找到了,那么返回找到的节点。先自上而下找,回去的时候再层层往回传找的结果就可以找到要找的最近公共子节点。
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return helper(root,p,q);
}
TreeNode* helper(TreeNode* root,TreeNode* p,TreeNode* q)
{
if(!root) return root;
if (root->val==p->val||root->val==q->val) return root;
TreeNode *left,*right;
left = helper(root->left,p,q);
right = helper(root->right,p,q);
if (left&&right) return root;
return left?left:right;
}