[关闭]
@snuffles 2019-04-04T16:56:53.000000Z 字数 1368 阅读 918

L236 二叉树的最近公共祖先


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

解:用递归思想来做,p,q要不在同侧,要不在异侧。
1)在左右子树分别返回p,q位置,当前节点为最小父节点。
2)同在左侧,左子树返回p,q中较高的一个,或者递归为1
3)同在右侧同理

减少点儿递归的次数t10%,s0%,当p,q在同一侧的时候,且不为p,q其中一个,不用再继续找了

  1. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  2. if(!root || p==root || q==root) return root;
  3. TreeNode* left = lowestCommonAncestor(root->left,p,q);
  4. if(left && left!=p && left!=q) return left;
  5. TreeNode* right = lowestCommonAncestor(root->right,p,q);
  6. if(right && right!=p&& right!=q) return right;
  7. // p,q in different sides;
  8. if(left && right) return root;
  9. // p,q both in left;
  10. if(left) return left;
  11. // p,q both in right;
  12. else return right;
  13. }

递归,分别看Left,right是否存在,t10%,s0%

  1. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  2. if(!root || p==root || q==root) return root;
  3. TreeNode* left = lowestCommonAncestor(root->left,p,q);
  4. TreeNode* right = lowestCommonAncestor(root->right,p,q);
  5. // p,q in different sides;
  6. if(left && right) return root;
  7. // p,q both in left;
  8. if(left) return left;
  9. // p,q both in right;
  10. else return right;
  11. }

原答案t10%,s0%

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