Java code?what is wrong with my code? thank you


  • 0
    K

    public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    List<TreeNode> list=new ArrayList<TreeNode>();
    List<TreeNode> list_l=findNode(p,root,list);
    List<TreeNode> list_h=findNode(q,root,list);
    for(int i=list_l.size()-1;i>=0;i++){
    for(int j=list_h.size()-1;j>=0;j++){
    if(list_l.get(i).val==list_h.get(j).val){
    return list_h.get(j);
    }
    }
    }
    return root;
    }

    public List<TreeNode> findNode(TreeNode node,TreeNode root,List<TreeNode> list){
        if(root!=null&&root.val!=node.val){
        List<TreeNode> tmp=list;
        tmp.add(root);
        List<TreeNode> tmp_l=findNode(node,root.left,tmp);
        List<TreeNode> tmp_r=findNode(node,root.right,tmp);
        if(tmp_l!=null){
            return tmp_l;
        }
        if(tmp_r!=null){
            return tmp_r;
        }
        }else if(root==null){
            return null;
        }else if(root!=null&&root.val==node.val){
            List<TreeNode> tmp=list;
            tmp.add(root);
            return tmp;
        }
        
        return null;
    }
    

    }


  • 0
    T

    One thing which could be wrong with your code is root.val==node.val . Since duplicates are possible you could be looking at wrong treenode. Instead do root == node


Log in to reply
 

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