剑指 Offer 68 - I. 二叉搜索树的最近公共祖先

给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。

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

例如,给定如下二叉搜索树:  root = [6,2,8,0,4,7,9,null,null,3,5]

示例 1:

2 
8 
6

一开始的想法是用双端队列,遍历两次,第一次记录p的祖先节点,第二次记录q的祖先节点,之后进行比对
复制代码
class Solution {
public:

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        deque<TreeNode*> sp;
        deque<TreeNode*> sq;
        Pan(root, p, sp);
        Pan(root, q, sq);
        TreeNode *ans = NULL;
        while (sp.front() == sq.front()) {
            ans = sp.front();
            sp.pop_front();
            sq.pop_front();
        }
        return ans;
    }
    void Pan(TreeNode* root, TreeNode* p, deque<TreeNode*> &sp) {
        if (root == NULL)
            return;
        if (!sp.empty()&&sp.back()==p) {
            return;
        }
        else {
            sp.emplace_back(root);
            Pan(root->left, p, sp);
            Pan(root->right, p, sp);
        }

        if (sp.back() != p) {
            sp.pop_back();
        }
    }
};
复制代码

后面看了解法是。发现自己忽略了这是个搜索树

复制代码
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;
    }
};
复制代码

 

 

posted on   4小旧  阅读(24)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示