Can someone help to check my solution output limit exceed


  • 0
    Y
    /**
    
    • Definition for a binary tree node.
    • public class TreeNode {
    • public int val;
      
    • public TreeNode left;
      
    • public TreeNode right;
      
    • public TreeNode(int x) { val = x; }
      
    • }
      */
    public class Solution {
    
      //use memery to save the contain root and target, so no need to check again
      Dictionary<TreeNode,Dictionary<TreeNode,bool>> memarizeSearchResult = new       Dictionary<TreeNode,Dictionary<TreeNode,bool>>();
    
    public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        
        //check null
        if(root==null)
            return root;
            
        //check if anyone is the root
        if(p==root)
            return root;
        if(q==root)
            return root;
        
        //check if anyone in the left
        
        if(IsContainReal(root.left, p) && IsContainReal(root.left, q))
            return LowestCommonAncestor(root.left, p, q);
        
        //check if anyone in the right
        if(IsContainReal(root.right, p) && IsContainReal(root.right, q))
            return LowestCommonAncestor(root.right, p, q);
            
        return root;
    }
    
     public bool IsContainReal(TreeNode root, TreeNode target)
    {
    
        if(root==null)
                return false;
        if(root==target)
                return  true;
     
        return IsContain(root.left,target) || IsContain(root.right,target);
    }
    
    public bool IsContain(TreeNode root, TreeNode target)
    {
        if(root==null)
                return false;
        if(!memarizeSearchResult.ContainsKey(root))
        {
            var newDic=new Dictionary<TreeNode,bool>();
            newDic.Add(target,false);
            memarizeSearchResult.Add(root,newDic);
            memarizeSearchResult[root][target] = IsContainReal(root,target);
        }
        
        if(!memarizeSearchResult[root].ContainsKey(target))
        {
            memarizeSearchResult[root].Add(target,false);
            memarizeSearchResult[root][target] = IsContainReal(root,target);
        }
        
        return  memarizeSearchResult[root][target];
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.