0
点赞
收藏
分享

微信扫一扫

二叉搜索树的最近公共祖先————附带详细代码和解析

萨科潘 2022-01-12 阅读 48

文章目录

1 题目

在这里插入图片描述

2 解析

2.1 法1

节点ancestor从根节点向下遍历,

  • 如果ancestor->val同时小于q->valp-val,那么公共祖先就在ancestor的右边;
  • 如果ancestor->val同时大于q->valp-val,那么公共祖先就在ancestor的左边;
  • 如果ancestor->val不同时小于或大于q->valp-val,那么它就是分岔节点(即两个节点的公共祖先);

2.2 法2

同时遍历根节点到qp的路径,公共祖先节点就是路径上最后一个相同的节点。

2.2 法2

3 代码

3.1

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* ancestor = root;
        while (true){
            if(p->val < ancestor->val && q->val < ancestor->val){
                ancestor = ancestor->left;
            }else if(p->val > ancestor->val && q->val > ancestor->val){
                ancestor = ancestor->right;
            }else{
                break;
            }
        }
        return ancestor;
    }
};

3.2 代码

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        auto getPath = [](TreeNode* root, TreeNode* target){
            auto func = [&](auto && self, TreeNode* root, TreeNode* target){
                vector<TreeNode*> path;
                TreeNode* node = root;
                while(node != target){
                    path.emplace_back(node);
                    if(target->val > node->val){
                        node = node->right;
                    }else{
                        node = node->left;
                    }
                }
                path.emplace_back(node);
                return path;
            };
            return func(func, root, target);
        };

        vector<TreeNode*> pPath = getPath(root, p);
        vector<TreeNode*> qPath = getPath(root, q);
        TreeNode* ancestor;
        for(int i = 0;i < pPath.size() && i < qPath.size();i++){
            if(pPath[i] == qPath[i]){
                ancestor = pPath[i];
            }else{
                break;
            }
        }
        return  ancestor;
    }
};
举报

相关推荐

0 条评论