[关闭]
@snuffles 2019-04-04T16:37:09.000000Z 字数 996 阅读 835

L235 二叉搜索树的最近公共祖先


给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

解:p,q可以都在左子树,都在右子树或者一边一个。
用递归来解

非递归写法,用一个循环来判断0.98%,0%

  1. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  2. while(true){
  3. if(root->val > max(p->val,q->val)){
  4. root =root->left;
  5. }
  6. else if(root->val < min(p->val,q->val)){
  7. root =root->right;
  8. }
  9. else break;
  10. }
  11. return root;
  12. }

递归写法 //0.98%,0%

  1. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  2. if(!root) return NULL;
  3. TreeNode* res;
  4. if(root->val > max(p->val,q->val)){
  5. res = lowestCommonAncestor(root->left,p,q);
  6. }
  7. else if(root->val < min(p->val,q->val)){
  8. res = lowestCommonAncestor(root->right,p,q);
  9. }
  10. else res = root;
  11. return res;
  12. }

//递归写法// 0.98%,0%

  1. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  2. if( root == NULL) return NULL;
  3. TreeNode * res;
  4. if( p->val < root->val && q->val < root ->val){
  5. res = lowestCommonAncestor(root->left,p,q);
  6. }
  7. else if( p->val > root->val && q->val > root ->val){
  8. res = lowestCommonAncestor(root->right,p,q);
  9. }
  10. else res = root;
  11. return res;
  12. }
  13. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注