首页 » 编程之美 » 正文

[leetcode_235]Lowest Common Ancestor of a Binary Search Tree

求二叉树中两个节点的最邻近公共祖先。以前做过类似的题目,但是确实好久没A题了,自己想了下。深度优先搜索,然后分别求出两条路径再求交,开始担心会超时,结果AC挺快的。

class Solution {
public:
    bool isFind;
    vector&lt;TreeNode <em>&gt; pV, qV;
    void FindK(TreeNode</em> node, TreeNode* k, vector&lt;TreeNode <em>&gt; &amp;kV)
    {<br />
        kV.push_back(node);
        if (isFind || node == k)
        {
            isFind = true;
            return;
        }
        if (NULL != node-&gt;left)
        {
            FindK(node-&gt;left, k, kV);
            if (isFind)
            {
                return;
            }
            kV.pop_back();
        }
        if (NULL != node-&gt;right)
        {
            FindK(node-&gt;right, k, kV);
            if (isFind)
            {
                return;
            }
            kV.pop_back();
        }
    }
    TreeNode</em> lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (NULL == root)
        {
            return root;
        }
        pV.clear();
        qV.clear();
        isFind = false;
        FindK(root, p, pV);
        isFind = false;
        FindK(root, q, qV);
        int i = 0;
        int minSize = pV.size() &gt; qV.size() ? qV.size() : qV.size();<br />
        for (i = 0;i &lt; minSize; i++)
        {
            if (pV[i] != qV[i])
            {
                break;
            }
        }
        return pV[i - 1];
    }
};

发表评论