-1

Im trying to make it right now using recursion but Im having a hard time, I think I have a logical error.

please someone help me T_T

Here is my code so far

    import java.util.ArrayList;
    public class BTNode{
        private BTNode root, left,right;
        private int item;

    public BTNode(int item){
        this(item,null,null,null);
    }
    public BTNode(int item, BTNode left, BTNode right, BTNode root,int count){
        this.item = item;
        this.left = left;
        this.right = right;
        this.root = root;
      this.count=count;
    }
    public void build(){
        this.left = new BTNode(40);
        this.left.root = this;

        this.right = new BTNode(100);
        this.right.root = this;

        this.left.right = new BTNode(45);
        this.left.right.root = this.left;

        this.left.left = new BTNode(25);
        this.left.left.root = this.left;

        this.right.left = new BTNode(70);
        this.right.left.root = this.right;

        this.right.right = new BTNode(200);
        this.right.right.root = this.right;

    }
    public void inorder(){//recursion
        //traverse the left
        if(left != null)
            left.inorder();
        //visit the root do the item
        System.out.print(this.item+" ");
        //traverse the right
        if(right != null)
            right.inorder();
    }
    public String inToString(){
        return ((left == null)?"": left.inToString()) + item + " " + ((right == null)?"": right.inToString()+" ");
    }
    //preorder()
    public void  preorder(){

      //visit the root do the item
        System.out.print(this.item+" ");
      //traverse the left
        if(left != null)
            left.preorder();
        //traverse the right
        if(right != null)
            right.preorder();
    }
   //preToString()
    public String preToString(){
        return item+ " "+((left == null)?"": left.preToString())+ ((right == null)?"": right.preToString()+" ");
    }
    //postorder()
   public void  postorder(){
        //traverse the left
        if(left != null)
            left.postorder();
        //traverse the right
        if(right != null)
            right.postorder();
      //visit root do the item
      System.out.print(this.item+" ");

    }
   //postToString()
    public String postToString(){
        return ((left == null)?"": left.postToString()) + ((right == null)?"": right.postToString()+" ")+item+ " ";
    }



    //findsum-recursive
   public int findsum(){
      //traverse left,if null traverse to right then add the two item lastly add to the root
       return ((left == null)?0: left.findsum()) + ((right == null)?0: right.findsum())+item;
   }




    //findlevel-recursive
   public int findlevel(){
      //check left && right if it is not null then iterate method recursively
      if (left == null)
                return 0;
      else if(right == null)
            return 0;
      else
          return 1 + left.findlevel();
  }
  /*
    //ancestor-recursive
   public BTNode ancestor(int value){
      if(left.count== 2){//check the root
         return left.ancestor();//traverse left node
      }
      System.out.print(item+" ");//print item if the left turns false
      if(root != null){
         right.ancestor();//traverse right node
      }
   }*/



   public int count(){
      //check if left || right are null then return 0, otherwise method were recursively executed
      return (((left==null)?0:1+left.count())+((right==null)?0:1+right.count()));
   }

   public void reference(){
      //check left != null print the root, traverse left, traverse right
      if(left != null)
         left.reference();
      if(left != null)
         System.out.print(item+" ");
      if(right != null)
         right.reference();

   }
   public void sort(){

   }
   public void insert(int given){
      BTNode node = new BTNode(given);

      if(item == 0)
         root = node;
      else
         {
            BTNode current = root; //points to the current Node
            BTNode parent; //points to the parent Node

            while(current != null)
            {
               if(item > given)
               {
                  parent = current;
                  current = left;
               }

               if(item < given)
               {
                  parent = current;
                  current = right;
               }
            }
            current = node;
            if(item < given)
               right = node;
            else
               left = node;
         }
        right.inorder();
   }
   public boolean contains(int given){
         return ((left==null)?false:left.contains(given))|| item==given || ((right == null)?false : right.contains(given));
         /*if(left != null)
            left.contains(given);
         if(right != null)
            right.contains(given);
         return item == given;*/
   }
    public static void main(String[]args){
        BTNode root = new BTNode(50);

        root.build();
        System.out.print("\nGiven :"+root.inToString());
        System.out.println("\ninorder");
        root.inorder();
        System.out.println("\npreorder");
        root.preorder();
      System.out.println("\npostorder");
        root.postorder();
      System.out.println("\nfindsum");
      System.out.println(root.findsum());
      System.out.println("\nfindlevel");
      //System.out.println(root.findlevel(200));
      System.out.println(root.findlevel());
      System.out.println("\nancestor");
      //System.out.println(root.ancestor());
      root.ancestor();
      System.out.println("\ncount");
      System.out.println(root.count());

      System.out.println("\nreference");
      //System.out.println(root.reference());
      root.reference();
      System.out.println("\nsort");
      //System.out.print(root.sort());
      root.sort();
      System.out.println("\nContains");
      System.out.println(root.contains(new Integer(70)));
      System.out.println("\ninsert");
      //System.out.print(root.sort());
      root.insert(new Integer(71));
          root.printinorder();
   }
}

please also check my insertion mechanism... I dont think that is the right way to do it

Dev2017
  • 857
  • 9
  • 31
Amits
  • 19
  • 7
  • or maybe give me some of your advices... Please – Amits Mar 12 '17 at 09:12
  • please add more explanation on your logic and why you did so as well as what exactly you are trying to achieve. – Dev2017 Mar 12 '17 at 09:21
  • greetings!! @DanishAlsayed how would i possibly implement a code for finding the lowest common ancestor of my binary tree? given only one node...like root.ancestor(25)...then the output would be 50 in recursive – Amits Mar 12 '17 at 13:41
  • can you clarify more? Whose ancestor? Roots do not have ancestors. Or do you mean given a node in the tree you want to find the smallest ancestor? What do you mean by common, common has to be for more than one node. Take a look at this http://stackoverflow.com/questions/12085869/lca-of-binary-tree-issue?rq=1 – Dev2017 Mar 12 '17 at 13:50
  • @DanishAlsayed I apologize...yes thats exactly what i mean..but given only one node...(20 40 45 50 70 100 200 inorder) like ancestor(25) = 50 not ancestor(25,70)=50... ugghhh im terrible at explaining im so sorry – Amits Mar 12 '17 at 14:08
  • do you want predecessor or ancestor? Moreover, 25 doesn't exist in the tree you showed. If you mean predecessor, then in in-order the tree is sorted in ascending, so the node right before the one in question is the answer. – Dev2017 Mar 12 '17 at 14:24
  • @DanishAlsayed im really sorry... i mean(25 40 45 50 70 100 200 inorder) – Amits Mar 12 '17 at 14:28
  • so do you mean the minimum ancestor of a given pair of nodes? – Dev2017 Mar 12 '17 at 14:29
  • @DanishAlsayed given only one node not pair – Amits Mar 12 '17 at 14:44
  • so given a node, you want the minimum ancestor? – Dev2017 Mar 12 '17 at 14:46
  • @DanishAlsayed yes exactly..please help me out.. it cant take it out of my mind – Amits Mar 12 '17 at 14:58

1 Answers1

1

Since your question is unclear, I am answering both of your potential questions.

1- If you want to find the minimum ancestor of a node, what you can do is given a node keep traversing up its parents while keeping a track of the smallest parent value found so far. Once you reach the root node you will have the smallest value. The time complexity of this algorithm is O(h) where h is the height of the tree. As this is very simple I am not giving a code sample here.

2- If you want to find the LCA (which is what you question title is about) you can do something very similar. If we assume that the keys n1 and n2 are present in Binary Tree, we can find LCA using single traversal of Binary Tree and without extra storage for path arrays. The idea is to traverse the tree starting from root. If any of the given keys (n1 and n2) matches with root, then root is LCA (assuming that both keys are present). If root doesn’t match with any of the keys, we recur for left and right subtree. The node which has one key present in its left subtree and the other key present in right subtree is the LCA. If both keys lie in left subtree, then left subtree has LCA also, otherwise LCA lies in right subtree. Here is an example code that you can tailor according to your need (this code works):

//Java implementation to find lowest common ancestor of
// n1 and n2 using one traversal of binary tree

/* Class containing left and right child of current
 node and key value*/
class Node
{
    int data;
    Node left, right;

    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}

public class BinaryTree
{
    //Root of the Binary Tree
    Node root;

    Node findLCA(int n1, int n2)
    {
        return findLCA(root, n1, n2);
    }

    // This function returns pointer to LCA of two given
    // values n1 and n2. This function assumes that n1 and
    // n2 are present in Binary Tree
    Node findLCA(Node node, int n1, int n2)
    {
        // Base case
        if (node == null)
            return null;

        // If either n1 or n2 matches with root's key, report
        // the presence by returning root (Note that if a key is
        // ancestor of other, then the ancestor key becomes LCA
        if (node.data == n1 || node.data == n2)
            return node;

        // Look for keys in left and right subtrees
        Node left_lca = findLCA(node.left, n1, n2);
        Node right_lca = findLCA(node.right, n1, n2);

        // If both of the above calls return Non-NULL, then one key
        // is present in once subtree and other is present in other,
        // So this node is the LCA
        if (left_lca!=null && right_lca!=null)
            return node;

        // Otherwise check if left subtree or right subtree is LCA
        return (left_lca != null) ? left_lca : right_lca;
    }

    /* Driver program to test above functions */
    public static void main(String args[])
    {
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(6);
        tree.root.right.right = new Node(7);
        System.out.println("LCA(4, 5) = " +
                            tree.findLCA(4, 5).data);
        System.out.println("LCA(4, 6) = " +
                            tree.findLCA(4, 6).data);
        System.out.println("LCA(3, 4) = " +
                            tree.findLCA(3, 4).data);
        System.out.println("LCA(2, 4) = " +
                            tree.findLCA(2, 4).data);
    }
}

This is method and code are from http://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/ on this site you can run the code in IDE as well online.