sábado, 2 de julho de 2022

Hacker Rank - Binary tree (Java)

 This was my approach, it can be improved (I saw other better solution), but this works.

  1. Get parents by searching the node in tree recursivelly for each value
  2. Compare the list of parent, the first to be found is common lesser ancestor


    public static Node lca(Node root, int v1, int v2) {
        // Write your code here.
          Node result = root;
          List<Node> parentsV1 = new ArrayList<Node>();
          List<Node> parentsV2 = new ArrayList<Node>();
          setParent(root, v1, parentsV1);
          setParent(root, v2, parentsV2);   
         
         // compare parents
          for (int i =0; i<parentsV1.size(); i++){
             for (int j=0; j< parentsV2.size();j++){
                 if (parentsV2.get(j).data== parentsV1.get(i).data)
                 result = parentsV1.get(i);
         }
          }
          

          return result;

    }
    
    // returns the list of parents
    public static void setParent( Node node, int value,List<Node> parents ){
        //search node
        if (node==null){
            //enpty do nothing
            return;

        } else if (node.data==value){
            // self can be also a common ancestor
            parents.add(node);
            return;
        }else{
            parents.add(node);
            if (node.data>value){
            setParent(node.left, value,parents);}
            else{
            setParent(node.right, value, parents);    }       
        }
    }

Sem comentários:

Enviar um comentário