p62 二叉树中节点的最近公共祖先 (leetcode 236)

一:解题思路

从根节点到当前节点p的经过的路径节点记录下来到ppath数组中,从根节点到当前的节点q的经过的节点记录下来到qpath中,对比这2个数组中最后相同的那个节点,并且将其返回即可。Time:O(n),Space:O(n)

二:完整代码示例 (C++版和Java版)

C++:

class Solution 
{
public:
    int min(int a, int b) { return a < b ? a : b; }

    bool search(TreeNode* root, TreeNode* node, vector<TreeNode*>& path)
    {
        if (root == NULL) return false;
        path.push_back(root);
        if (root == node) return true;
        bool ret = search(root->left,node,path)||search(root->right,node,path);
        if (ret) return ret;
        path.pop_back();
        return false;
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
    {
        vector<TreeNode*> ppath;
        vector<TreeNode*> qpath;

        search(root,p,ppath);
        search(root,q,qpath);

        int i = 0, len = min(ppath.size(),qpath.size());

        while (i < len && ppath[i] == qpath[i]) i++;

        return qpath[i-1];
    }
};

Java:

class Solution {
    private boolean search(TreeNode root,TreeNode node,List<TreeNode> path)
    {
        if(root==null) return false;
        path.add(root);
        if(root==node) return true;
        boolean ret=search(root.left,node,path)||search(root.right,node,path);
        if(ret) return true;
        path.remove(path.size()-1);
        return false;
    }
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) 
    {
        List<TreeNode> ppath=new ArrayList<>();
        List<TreeNode> qpath=new ArrayList<>();
        
        search(root,p,ppath);
        search(root,q,qpath);
        
        int i=0,len=Math.min(ppath.size(),qpath.size());
        while(i<len && ppath.get(i)==qpath.get(i)) i++;
        
        return ppath.get(i-1);
    }
}

猜你喜欢

转载自www.cnblogs.com/repinkply/p/12524803.html