Runtime error !


  • 0
    T

    Can anyone tell me what is wrong with my code ?
    This is the error I received:

    Line 41: java.lang.StackOverflowError

    import java.util.*;
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            List<TreeNode> pList = findParents(root, p);
            List<TreeNode> qList = findParents(root, q);
            if(pList.size() == 0 || qList.size() == 0)
                return null;
            else
            {
                TreeNode p1 = pList.get(0);
                for(int i = 0; i + 1 < pList.size() && i+1<qList.size(); i++)
                {
                    if(pList.get(i+1) != qList.get(i+1))
                    {
                        p1 = pList.get(i);
                        break;
                    }
                }
                return p1;
            }
        }
        public List<TreeNode> findParents(TreeNode root, TreeNode p)
        {
            List<TreeNode> myList = new ArrayList<>();
            if(root == null)
                return myList;
            if(root == p)
            {
                myList.add(root);
                return myList;
            }
            List<TreeNode> left = findParents(root.left, p);
            if(left.size() != 0)
            {
                myList.add(root);
                myList.addAll(left);
                return myList;
            }
            else
            {
                List<TreeNode> right = findParents(root.right, p);
                if(right.size() == 0)
                    return myList;
                else
                {
                    myList.add(root);
                    myList.addAll(right);
                    return myList;
                }
            }
        }
    }

Log in to reply
 

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