Same case but different output ?


  • 0
    L

    I changed the code, but nothing happened... I still stuck in the same test case...

    The test case is [3,1,4,null,2], the two nodes are 2 and 3. I run the code on my computer and it returns 3, but when I submitted it here, its output turns into 2. I don't konw what's going on...

    public class Solution {
            
        public static ArrayList<TreeNode> pathP = new ArrayList<>();
        public static ArrayList<TreeNode> pathQ = new ArrayList<>();
    
        public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            
            helper(root, p, pathP);
            helper(root, q, pathQ);
    
            for (int i = 0; i < pathP.size(); i++) {
                for (int j = 0; j < pathQ.size(); j++) {
                    if (pathP.get(i) == pathQ.get(j)) {
                        return pathP.get(i);
                    }
                }
            }
    
            return null;
        }
    
        public static int helper(TreeNode root, TreeNode t, ArrayList<TreeNode> path) {
            if (t == root) {
                path.add(root);
                return 1;
            } else if (root.left != null && t.val < root.val) {
                int a = helper(root.left, t, path);
                if (a == 1) {
                    path.add(root);
                    return 1;
                }
            } else if (root.right != null && t.val > root.val) {
                int b = helper(root.right, t, path);
                if (b == 1) {
                    path.add(root);
                    return 1;
                }
            }
            return 0;
        }
    }

Log in to reply
 

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