My code is giving me Time Limit Exceeded. Can someone please help what am I doing wrong?


  • 0
    D
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            if(root == null){
                return null;
            }if((p.val == root.val) || (q.val == root.val)){
                return root;
            } 
            boolean leftChildP = isLeftChild(root,p);
            boolean leftChildQ = isLeftChild(root,q);
            if((isRightChild(root,p)) && leftChildQ){
                return root;
            }if((isRightChild(root,q)) && leftChildP){
                return root;
            }
            if(leftChildP && leftChildQ){
                    return lowestCommonAncestor(root.left,p,q);}
                else{
                    return lowestCommonAncestor(root.right,p,q);}
            }
            
        private boolean isLeftChild(TreeNode root, TreeNode node){
            if (root == null){
                return false;
            }if(root.left == null){
                return false;
            }else{
                return isChild(root.left,node);
            }}
        
        
        private boolean isRightChild(TreeNode root, TreeNode node){
            if(root == null){
                return false;
            }if(root.right == null){
                return false;
            }else{
             return isChild(root.right,node);   
            }}
        
        
        private boolean isChild(TreeNode parent, TreeNode child){
            if(parent == null){
                return false;}
            if(parent.left == null && parent.right == null){
                return false;}
            if(parent.left == null){
                if(parent.right.val == child.val){
                    return true;
                }else{return isChild(parent.right,child);}
            }else{
                if(parent.left.val == child.val){
                    return true;
                }else{return isChild(parent.left,child);}
            }
            
            
        }
    }

Log in to reply
 

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