您的位置:首页 > 其它

一颗普通的二叉树,如何寻找两个节点的最低公共祖先(发现的一个与算法无关的引用问题)

2015-08-12 14:23 633 查看
      算法很简单:先通过DFS深度优先遍历二叉树,找到两个节点的路径(从root开始),保存两个路径,然后比较两个路径中相同位置的节点是否是同一个节点。如果是最后一个相同的节点,那么就是最低公共祖先。

     先上代码吧,/**

 * Definition for a binary tree node.

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

      //首先前序遍历二叉树,得到从root到p,q的路径

      vector<TreeNode*> rode1;

      vector<TreeNode*> rode2;

      FindPath(root, p, rode1);

      FindPath(root, q, rode2);

 

      TreeNode* result;

      for(int i=0 ;i<min(rode1.size(),rode2.size());++i){ 

            if(rode1[i]==rode2[i])

                result = rode1[i];

      }

      return result;

    }

    

    bool FindPath(TreeNode*root, TreeNode* end, vector<TreeNode*> path)

    {

        if(root == NULL)

            return false;

        if(root== end)

        {

            path.push_back(root);

            return true;

        }

            

        path.push_back(root);

        

        bool found = false;

        if(!found)

            found = FindPath(root->left, end, path);

        if(!found)

            found = FindPath(root->right, end, path);

        if(!found)

            path.pop_back();

        return found;

    }

};

这是我最开始的代码,提交到leetcode的时候显示内存不够。最后发现问题出在标红的那一行,传递vetcor的时候传递用得是传值,最后会把整个vector复制一遍。当把vector改为传引用,即&path后accept.其实以前就知道如果传递大量数据作为形参的时候应该用引用&,但是还是在写代码的时候忘记了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: