p62 binary recent common ancestor of nodes (leetcode 236)

A: problem-solving ideas

After the current path from the root node to node p ppath array to record, record from the root node to node q through current down to qpath, the contrast of these two nodes that last the same array, and return it to. Time: O (n), Space: O (n)

Two: Complete code examples (C ++ version and the Java version)

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);
    }
}

 

Guess you like

Origin www.cnblogs.com/repinkply/p/12524803.html