xxxl_eet
xxxl_eet

Reputation: 15

systemverilog: Binary tree using systemverilog oop concepts

i was wondering since systemverilog has oops concepts. Is it possible to create binary tree of n nodes in systemverilog

class node;

    int val;
    node left,right;
    function new(int data);
        val=data;
        left=null;
        right=null;
    endfunction
endclass

class btree;

    node root;

    function new(int info);
        root=new(info); 
    endfunction

endclass

btree b1;

module abc();
    
    initial begin
        b1=new(1);
        b1.root=new(2)
        b1.root.left= new(3);
        b1.root.right= new(4);

        $display("%0p",b1);
    end
endmodule

i am trying to create a binary tree capable of adding any number of nodes, delete nth node and could tranverse through tree to print.

Upvotes: 0

Views: 484

Answers (1)

Serge
Serge

Reputation: 12344

Since there is no clear question, there is no clear answer. The following is just a place holder for an example which might or might not allow you to move forward a bit.

When you do $display(b1) it only supposed to print some info about the b1 which is an instance of class 'btree'. So, there is not much. If you want to print info about all branches and leaves, you need to create a (recursive) function which would do it.

The following example provides such a function 'print'. You can use it as a starting point for your tree exploration. You also need to implement some code to insert new nodes (or delete, if you need). If you need a balanced tree, you need to add corresponding balancing functionality.

Also, remember that this code is not synthesizable and can only be used in test benches. Synthesizable code will require a completely different approach.

class node;

    int val;
    node left,right;
    function new(int data);
        val=data;
        left=null;
        right=null;
    endfunction

  /// print function ///
  function void print();
    $display("val: %0d", val);
    if (left != null)
      left.print();
    if (right != null)
      right.print();
  endfunction
endclass

class btree;

    node root;

    function new(int info);
        root=new(info); 
    endfunction

endclass

btree b1;

module abc();
    
    initial begin
        b1=new(1);
      b1.root=new(2);
        b1.root.left= new(3);
        b1.root.right= new(4);

        //$display("%0p",b1);
      // use the print function
      b1.root.print();
    end
endmodule

Upvotes: 1

Related Questions