What if the input is not TreeNode, but the value? How to handle the duplicate case?

  • 0

    I failed to pass the test case

    Use the following code:

    public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    return lca(root, p, q);

    private TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null)
            return root;
        if(root.val == q.val|| root.val == p.val)
            return root;
        TreeNode lca_left = lca(root.left, p, q);
        TreeNode lca_right = lca(root.right, p, q);
        if( lca_left != null && lca_right != null) {
            return root;
        return lca_left == null? lca_right : lca_left;


    I realise that the problem lies in if(root.val == q.val|| root.val == p.val). Since there are two -100 this program return the root. But what if the input is not treeNode but int value? How to modified the program to make it right?

Log in to reply

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