How to serialize a binary tree object

HI Friends,
This is the problem.............................
I got a binary Tree Program with root (object ) containing the elements in the tree.
I got a server which performs insertions and deletions in the root.
Once it has got the operations right it has to send this object to client and Client will perform the search over this Binary Tree.
How to do this................................ Any Idea
Anyone can get me the Code....... It will be great to u....
reply me in this Id : [email protected]

Have you looked at the TreeSet code.
This is a collection which stores data as a binary tree. It is serializable, has a look at the readObject and writeObject methods.

Similar Messages

  • How to crossover this binary tree..?

    You can view detail http://www.codeguru.com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
    [nha khoa|http://www.sieuthi77.com/main/nhakhoa.html] .com/forum/showthread.php?s=bb4cf7ad2b18a5115e8bd6ab3a4e9d17&t=470868
    I have these classes which model a tree (binary). the thing is i cant figure out how i can set the elements of individual nodes in that tree. i can get individual elements but i cannot set them due to the strucutre of the tree and how it is implemented. The changes that I make to these classes should be as less as possible, because i have an algorithm which generates the tree structure randomly, plus i can evaluate the tree easily by using recursion. The only left thing to do is CROSSOVER but how?!?
    here are the classes which model my binary tree:
    Code:
    public abstract class Node implements Cloneable{
    abstract double evaluate(VariableInput v);
    abstract String print();
    abstract int getNumberOfNodes();
    abstract ArrayList<Object> getChildren();
    @Override
    public Node clone(){
    Node copy;
    try {
    copy = (Node) super.clone();
    } catch (CloneNotSupportedException unexpected) {
    throw new AssertionError(unexpected);
    //In an actual implementation of this pattern you might now change references to
    //the expensive to produce parts from the copies that are held inside the prototype.
    return copy;
    Code:
    public class UnaryNode extends Node {
    private UnaryFunction operator;
    private Node left;
    public UnaryNode(UnaryFunction op, Node terminal) {
    operator = op;
    this.left = terminal;
    public String print(){
    String r = "(" + operator.toString()+ " " + left.print() + ")";
    return r;
    void setLeft(Node left) {
    this.left = left;
    @Override
    int getNumberOfNodes() {
    return 1 + left.getNumberOfNodes();
    Node getLeft() {
    return left;
    ArrayList<Object> getChildren() {
    ArrayList<Object> arr = new ArrayList<Object>();
    arr.add(this);
    arr.addAll(left.getChildren());
    return arr;
    Code:
    public class BinaryNode extends Node {
    private BinaryFunction operator;
    private Node left;
    private Node right;
    public BinaryNode(BinaryFunction op, Node left, Node right) {
    operator = op;
    this.left = left;
    this.right = right;
    public String print(){
    String r = "(" + operator.toString()+ " " + left.print() + " " + right.print()+")";
    return r;
    public void setLeft(Node left){
    this.left = left;
    public void setRight(Node right){
    this.right = right;
    @Override
    int getNumberOfNodes() {
    return 1 + left.getNumberOfNodes() + right.getNumberOfNodes();
    Node getRight() {
    return right;
    Node getLeft() {
    return left;
    @Override
    ArrayList<Object> getChildren() {
    ArrayList<Object> arr = new ArrayList<Object>();
    arr.add(this);
    arr.addAll(left.getChildren());
    arr.addAll(right.getChildren());
    return arr;
    public class NumericNode extends Node{
    private double value;
    public NumericNode(double v){
    value = v;
    @Override
    double evaluate(VariableInput c) {
    return value;
    public String print(){
    String r = "" + value;
    return r;
    @Override
    int getNumberOfNodes() {
    return 1;
    @Override
    ArrayList<Object> getChildren() {
    ArrayList<Object> arr = new ArrayList<Object>();
    arr.add(new NumericNode(value));
    return arr;
    }p.s. I have this get children method which return a list of REFERENCES to all the nodes in the tree, but if i change any of them it wont have an effect to the tree itself because they are references.
    Any ideas or codes will be much appreciated. Thanks!

    What? Changes to what a node is referencing will be reflected in the tree, unless your getChildren is returning a copy, like in NumericNode.
    Kaj

  • How to make a binary tree

    i have this assignment for school. The first thing it says is: Write a binary tree class named my_Tree as the basic data structure. What does this mean? Can anyone give me an example of the java code that this should be written in?
    Also, i have to sort a sequence of numbers in increasing order. I have the command line prompt written already, but how do i sort it using if/else statements? Thanks a lot. I'm really bad at java programming.

    i dont really understand that? Im really slow at
    this. Can you clarify?Sorry. Here is a more complete implementation of a node.
    // header file for class Node
    // copywrong filestream. no rights reserved
    #ifndef _NODE_H_
    #define _NODE_H_
    class Node
       public:
          Node();
          Node(int x);
          Type getinfo();
          Node *getleft();
          Node *getright();
          void setinfo(Type x);
          void setleft(Node *n);
          void setright(Node *n);
       private:
          int info;
          Node *left;
          Node *right;
    #endif

  • How to  Serialize a very big Object??

    Please help me !

    I misread that as sterilize for a moment. Buckets and buckets of dettol! And that's the clean answer.
    As Athena indicates you Serialize a very big Object in exactly the same way that you Serialize a very small object.
    Are you encountering a problem, and if so what is it?
    Dave.

  • A Binary Tree Implementation in ABAP

    Hi,
    Can any one explaine me how to create a binary tree of random numbers with dynamic objects.
    Thanks,
    Manjula.

    Hi manjula,
    This sample code uses dynamic objects to create a binary tree of random numbers as per your requirement ...pls go through It. 
    It stores numbers on the left node or right node depending on the value comparison with the current value. There are two recursive subrotines used for the building of the tree and printing  through the tree.
    For comparison purpose, the same random numbers are stored and sorted in an internal table and printed.
    *& Report YBINTREE - Build/Print Binary Tree of numbers *
    report ybintree .
    types: begin of stree,
    value type i,
    left type ref to data,
    right type ref to data,
    end of stree.
    data: tree type stree.
    data: int type i.
    data: begin of rnd occurs 0,
    num type i,
    end of rnd.
    start-of-selection.
    do 100 times.
    generate random number between 0 and 100
    call function 'RANDOM_I4'
    exporting
    rnd_min = 0
    rnd_max = 100
    importing
    rnd_value = int.
    store numbers
    rnd-num = int.
    append rnd.
    build binary tree of random numbers
    perform add_value using tree int.
    enddo.
    stored numbers are sorted for comparison
    sort rnd by num.
    print sorted random numbers
    write: / 'Sorted Numbers'.
    write: / '=============='.
    skip.
    loop at rnd.
    write: rnd-num.
    endloop.
    skip.
    print binary tree. This should give the same result
    as the one listed from the internal table
    write: / 'Binary Tree List'.
    write: / '================'.
    skip.
    perform print_value using tree.
    skip.
    *& Form add_value
    text - Build tree with value provided
    -->TREE text
    -->VAL text
    form add_value using tree type stree val type i.
    field-symbols: <ltree> type any.
    data: work type stree.
    if tree is initial. "When node has no values
    tree-value = val. " assign value
    clear: tree-left, tree-right.
    create data tree-left type stree. "Create an empty node for left
    create data tree-right type stree. "create an empty node for right
    else.
    if val le tree-value. "if number is less than or equal
    assign tree-left->* to <ltree>. "assign the left node to fs
    call add_value recursively with left node
    perform add_value using <ltree> val.
    else. "if number is greater
    assign tree-right->* to <ltree>. "assign the right node to fs
    call add_value recursively with right node
    perform add_value using <ltree> val.
    endif.
    endif.
    endform. "add_value
    *& Form print_value
    text - traverse tree from left-mid-right order
    automatically this will be sorted list
    -->TREE text
    form print_value using tree type stree.
    field-symbols: <ltree> type any.
    if tree is initial. "node is empty
    else. "non-empty node
    assign tree-left->* to <ltree>. "left node
    perform print_value using <ltree>. "print left
    write: tree-value. "print the current value
    assign tree-right->* to <ltree>. "right node
    perform print_value using <ltree>. "print right
    endif.
    endform. "print_value
    pls reward if helps,
    regards.

  • Emptying a Binary Tree

    Hello,
    The problem I'm having is how to empty a binary tree. Here is my code for MyBinaryTree:
    public class MyBinaryTree implements BinaryTree {
       private BinaryTreeNode root;
       protected static int numNodes;
       private static String tree = "";
        * Constructor that creates a binary tree with a root.
        * @param r The root node
        * @param num The number of nodes
       public MyBinaryTree(BinaryTreeNode r, int num) {
          root = r;
          numNodes = num;
        * Method to make the binary tree empty.
       public void makeEmpty() {
          root.left = null;
          root.right = null;
          root = new BinaryTreeNode(null,null,null,null,null);
          numNodes = 0;
        * Method to make a root with key k and element el.
        * @param k The key of the root
        * @param el The element in the root
       public void makeRoot(Comparable k, Object el) {
          root = new BinaryTreeNode(k,el);
          numNodes++;
        * Method to return the root of the binary tree.
        * @return The root of the tree
       public BinaryTreeNode root() {
          return root;
        * Method to return the left child of a node.
        * @param node The node whose left child is wanted.
        * @return The left child of the node
        * @see NoNodeException
       public BinaryTreeNode leftChild(BinaryTreeNode node) throws NoNodeException {
          if (node.left == null) throw new NoNodeException("No left child!");
          else return node.leftChild();
        * Method to set the left child of node "node".
        * @param node The node to be given a left child
        * @param child The node to be set as left child
       public void setLeftChild(BinaryTreeNode node, BinaryTreeNode child) {
          node.setLeftChild(child);
          numNodes++;
        * Method to return the right child of a node.
        * @param node The node whose right child is wanted.
        * @return The right child of the node
        * @see NoNodeException
       public BinaryTreeNode rightChild(BinaryTreeNode node) throws NoNodeException{
          if (node.right == null) throw new NoNodeException("No right child!");
          else return node.rightChild();
        * Method to set the right child of node "node".
        * @param node The node to be given a right child
        * @param child The node to be set as right child
       public void setRightChild(BinaryTreeNode node, BinaryTreeNode child) {
          node.setRightChild(child);
          numNodes++;
        * Method to return the parent of a node.
        * @param node The node whose parent is wanted.
        * @return The parent of the node
        * @see NoNodeException
       public BinaryTreeNode parent(BinaryTreeNode node) throws NoNodeException {
          if (node.p == null) throw new NoNodeException("No parent!");
          else return node.parent();
        * Method to set the parent of node "node".
        * @param node The node to be given a parent
        * @param pt The node to be set as parent
       public void setparent(BinaryTreeNode node, BinaryTreeNode pt) {
          node.setParent(pt);
          numNodes++;
        * Method to return the key of the specified node.
        * @param node The node with the key to be returned
        * @return The key of the node
       public Comparable getKey(BinaryTreeNode node) {
          return node.getKey();
        * Method to set the key of the specified node.
        * @param node The node for which the key will be set.
        * @param k The key to be set.
       public void setKey(BinaryTreeNode node, Comparable k) {
          node.setKey(k);
        * Method to get the element in the specified node.
        * @param node The node with the element to be returned.
        * @return The element in the node.
       public Object getElement(BinaryTreeNode node) {
          return node.getElement();
        * Method to put an element into the specified node.
        * @param node The node that will have an element put in it.
        * @param o The element to be inserted.
       public void setElement(BinaryTreeNode node, Object o) {
          node.setElement(o);
        * Method to add a left child to the specified node.
        * @param theNode The node that the left child will be added to.
        * @param k The key associated with the left child.
        * @param el The element in the left child.
       public void addLeftChild (BinaryTreeNode theNode, Comparable k, Object el) {
          BinaryTreeNode temp = new BinaryTreeNode(k,el);
          temp.setParent(theNode);
          theNode.setLeftChild(temp);
          numNodes++;
        * Method to add a right child to the specified node.
        * @param theNode The node that the right child will be added to.
        * @param k The key associated with the right child.
        * @param el The element in the right child.
       public void addRightChild (BinaryTreeNode theNode, Comparable k, Object el) {
          BinaryTreeNode temp = new BinaryTreeNode(k,el);
          temp.setParent(theNode);
          theNode.setRightChild(temp);
          numNodes++;
        * Method to remove the left child of the specified node.
        * @param theNode The node which the left child will be removed.
       public void removeLeftChild(BinaryTreeNode theNode) {
          ((BinaryTreeNode)(theNode.left)).p = null;
          theNode.left = null;
          numNodes--;
        * Method to remove the right child of the specified node.
        * @param theNode The node which the right child will be removed.
       public void removeRightChild(BinaryTreeNode theNode) {
          ((BinaryTreeNode)(theNode.right)).p = null;
          theNode.right = null;
          numNodes--;
        * Private method to perform an inorder traversal on the tree.
        * @param t A MyBinaryTree object
        * @param n The starting node.
       private static String inorderPrint(MyBinaryTree t, BinaryTreeNode n) {
          String spaces = "";
          for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
          if (n.left != null || n.right != null) inorderPrint(t,t.leftChild(n));
          tree += spaces + n.getElement();
          if (n.left != null || n.right != null) inorderPrint(t,t.rightChild(n));
          return tree;
        * Private method to perform an inorder traversal on the tree.
        * @param t A MyBinaryTree object
        * @param n The starting node.
        * @param pos The current position in the tree.
        * @return A tree with an asterix beside the current position
       private static String inorderPrint2(MyBinaryTree t, BinaryTreeNode n,
                                           BinaryTreeNode pos) {
          String spaces = "";
          for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
          if (n.left != null || n.right != null) inorderPrint2(t,t.leftChild(n),pos);
          if (n.getElement() == pos.getElement()) tree += spaces + n.getElement() + "*";
          else tree += spaces + n.getElement();
          if (n.left != null || n.right != null) inorderPrint2(t,t.rightChild(n),pos);
          return tree;
        * Method to return a String representation of the binary tree.
        * @return String representation of the binary tree
       public String toString() {
          if (root.getElement() == null) return "*** Tree is empty ***";
          else {
             MyBinaryTree temp = new MyBinaryTree(root,numNodes);
             return inorderPrint(temp,root);
        * Method to return a String of the binary tree with an asterix beside the
        * current position.
        * @param currentPosition The current position.
        * @return A String of the tree with an asterix by the current position
       public String toString(BinaryTreeNode currentPosition) {
          if (root.getElement() == null) return "*** Tree is empty ***";
          else {
             MyBinaryTree temp = new MyBinaryTree(root,numNodes);
             return inorderPrint2(temp,root,currentPosition);
    }Those are all the methods I'm allowed to have. When I run makeEmpty, it seems to work, but then if I do makeRoot, the old tree prints again. It's quite bizarre. Any tips on how to empty the tree correctly?

    Here is the BinaryTreeNode code.
    public class BinaryTreeNode {
        // Instance variables (Note: they are all "private")
        protected Comparable key;           // The key at this node
        protected Object element;          // The data at this node
        protected BinaryTreeNode left;     // Left child
        protected BinaryTreeNode right;    // Right child
        protected BinaryTreeNode p;        // The Parent
        // Constructors
        BinaryTreeNode( Comparable theKey, Object theElement, BinaryTreeNode lt,
                        BinaryTreeNode rt, BinaryTreeNode pt  ) {
            key      = theKey;
            element  = theElement;
            left     = lt;
            right    = rt;
            p        = pt;
        BinaryTreeNode( Comparable theKey, Object theElement) {
            key      = theKey;
            element  = theElement;
            left     = null;
            right    = null;
            p        = null;
        // return the key attached to this node
        public Comparable getKey() {
            return key;
        // set the key attached to this node to be Comparable k
        public void setKey(Comparable k) {
            key = k;
        // return the element attached to this node
        public Object getElement() {
            return element;
        // set the element attached to this node to be Object o
        public void setElement(Object o) {
            element = o;
        // return left child
        public BinaryTreeNode leftChild() {
            return left;
        // set left child to be node n
        public void setLeftChild(BinaryTreeNode n) {
            left = n;
        // return right child
        public BinaryTreeNode rightChild() {
            return right;
        // set right child to be node n
        public void setRightChild(BinaryTreeNode n) {
            right = n;
        // return parent
        public BinaryTreeNode parent() {
            return p;
        // set parent to be node n
        public void setParent(BinaryTreeNode n) {
            p = n;
    }

  • How to Pretty Print a Binary Tree?

    I'm trying to display a Binary Tree in such a way:
    ________26
    ___13_________2
    1_______4 3_________1
    (without the underscores)
    however I cannot figure out the display method.
    class BinaryNode
              //Constructors
              BinaryNode leftChild, rightChild;
    Object data;
         BinaryNode()
    leftChild = null;
    data = null;
    rightChild = null;
              BinaryNode( Object d, BinaryNode left, BinaryNode right)
    leftChild = left;
    data = d;
    rightChild = right;
              //Height
              public static int Height(BinaryNode root)
    if (root == null)
    return 0;
    if ((Height(root.leftChild)) > Height(root.rightChild))
    return 1 + Height(root.leftChild);
    return 1 + Height(root.rightChild);
              //Count
    public static int Count(BinaryNode root)
    if(root==null)
    return 0;
    return 1 + Count(root.leftChild) + Count(root.rightChild);
              //Display
              public static void Display(BinaryNode root)
              int level = 2^(Level(root)-1)
              for (int i = 1; i<Height(root)+1; i++)
              System.out.printf("%-4s%
              Display(root, i);
              System.out.println();
              public static void Display(BinaryNode root, int level)
              if (root!=null)
              if(level==1)
              System.out.print(root.data + " ");
              else
              Display(root.leftChild, level-1);
              Display(root.rightChild, level-1);
              //Level
              public static int Level(BinaryNode root)
              if(root==null)
              return 0;
              if(root.leftChild == null && root.rightChild == null)
              return 1;
              return Level(root.leftChild) + Level(root.rightChild);
    Edited by: 815035 on Nov 23, 2010 12:27 PM

    The example of what the OP wants it to look like I thought was quite plain. Its right at the top of the post.
    Unfortunately it is also quite difficult to accomplish using System.out.print statements.
    You have to print out the root of the tree first (its at the top)
    However you don't know how far along to the right you need to print it without traversing the child nodes already (you need to know how deep the tree is, and how far to the left the tree extends from the root)
    So you will need to traverse the tree at least twice.
    Once to work out the offsets, and again to print out the values.
    The working out of offsets would have to be a depth search traversal I think
    The printing of the values in this fashion would be a breadth first traversal.
    I remember (ages ago) doing a similar assignment, except we printed the tree sideways.
    ie the root was on the left, the leaves of the tree on the right of the screen.
    That meant you could do an inorder depth traversal of the tree to just print it once.
    hope this helps,
    evnafets

  • How to remember the path while traverse a binary tree?

    Hi, again, I have difficulty handling tree search problems.
    The quesion is How to search for a node from a binary tree A, return true if found meanwhile generate the path which can be used to locate the node.
    I think the signature should be:
    // The path contains only 0s and 1s. 0 means go left and 1 means go right.
    public staic boolean search(Node rootOfA, Node b, ArrayList<Integer> path){
    // the class Node only has two fields:
    Node{
    Node left;
    Node right;
    I know if there is another field in the Node class (say, a flag), the quesion would be much easier, but the space is really critical.
    I tried to use recursion but havn't got a correct solution. I am thinking of usinga non-recursion algo.
    Anyone wants to help?

    Hi, JosAh,
    That's mind provoking. However, I do think it works. It does not pop some stuff it should pop. I tested it over a very simple tree and it failed. Did you test it? I might be wrong...
    The tree I am working on does not have null pointers, the condition to test if a node is a leaf is if(node.right == right). Namly, all the right pointer of leaves points to itself.
    So I changed your code to be:
    Stack search(Node root, Node node, Stack<Integer> path) {
         if (root == null || root.right ==right) return null;
         if (root.equals(node)) return path;
         path.push(0);
    if (search(root.left, node, path) != null) return path;
    path.pop();
    path.push(1);
    return search(root.right, node, path);
    }I simply tested it with
    Stack<Integer> path = new Stack<Integer>();
    System.out.println( root, root.right.right, path);
    root is the root of a complete binary tree with 7 nodes(4 leaves).
    Apparenly, if the path is built correctly search(root, root.right.right, path) would return [1,1] whereas this seach returns [ 0 , 1, 1].
    Considerring , the right branch never pops, I changed it into
    Then I changed it to :
    Stack search(Node root, Node node, Stack<Integer> path) {
         if (root == null || root.right ==right ) return null;
         if (root.equals(node)) return path;
         path.push(0);
    if (search(root.left, node, path) != null) return path;
    path.pop();
    path.push(1);
    if (search(root.right, node, path) != null) return path;
    path.pop();
    return path;
    With the same test case, it returns [].
    I will keep working on it.
    Cheers,
    Message was edited by:
    since81
    Message was edited by:
    since81

  • How do we know if it's a leaf in a binary tree

    how do we know if a node is a leaf in a binary tree?

    Both the left and right nodes should be null.

  • How to extend  breadth first Search for Binary Tree to any kind of Tree??

    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ie each node has more than 2 leaves such as 1, 2,3,4 or any,
    I have following code to successfully apply for breadth first Search in Binary Tree as follows,
    package a.border;
    import java.util.ArrayList;
    import java.util.LinkedList;
    public class Tree
        int root;
        Tree left;
        Tree right;
        static ArrayList<Integer> list = new ArrayList<Integer>();
        static ArrayList<Tree> treeList = new ArrayList<Tree>();
        private static LinkedList<Tree> queue = new LinkedList<Tree>();
         * @param root root value
         * @param left left node
         * @param right right node
        public Tree(int root, Tree left, Tree right)
            this.root = root;
            this.left = left;
            this.right = right;
        /** Creates a new instance of Tree
         * You really should know what this does...
         * @param root
        public Tree(int root)
            this.root = root;
            this.left = null;
            this.right = null;
         * Simply runs a basic left then right traversal.
        public void basicTraversal()
            //Check if we can go left
            if (left != null)
                left.basicTraversal();
            //Add the root
            list.add(root);
            //Check if we can go right
            if (right != null)
                right.basicTraversal();
        public ArrayList<Integer> getBreadthTraversal(ArrayList<Integer> list)
            //Add the root to the arraylist, we know it is always the first entry.
            list.add(root);
            //Basically we add the first set of nodes into the queue for
            //traversing.
            //Query if left exists
            if (left != null)
                //Then add the node into the tree for traversing later
                queue.add(left);
            //Same for right
            if (right != null)
                queue.add(right);
            //Then we call the traverse method to do the rest of the work
            return traverse(list);
        private ArrayList<Integer> traverse(ArrayList<Integer> list)
            //Keep traversing until we run out of people
            while (!queue.isEmpty())
                Tree p = queue.remove();
                //Check if it has any subnodes
                if (p.left != null)
                    //Add the subnode to the back of the queue
                    queue.add(p.left);
                //Same for left
                if (p.right != null)
                    //Same here, no queue jumping!
                    queue.add(p.right);
                //Append to the ArrayList
                list.add(p.root);
            //And return
            return list;
         * Makes a tree and runs some operations
         * @param args
        public static void main(String[] args)
             *                             4
             *          t =           2       6
             *                      1   3    5   7
            Tree leaf6 = new Tree(1);
            Tree leaf7 = new Tree(3);
            Tree leaf8 = new Tree(5);
            Tree leaf9 = new Tree(7);
            Tree t4 = new Tree(2, leaf6, leaf7);
            Tree t5 = new Tree(6, leaf8, leaf9);
            Tree t = new Tree(4, t4, t5);
            t.basicTraversal();
            System.out.println("Here is basicTraversal ="+list.toString());
            list.clear();
            t.getBreadthTraversal(list);
            System.out.println("getBreadthTraversal= " +list.toString());
            list.clear();
        }Can Guru help how to update to any kind of tree??
    here this code is for the tree like:
             *                             4
             *          t =           2       6
             *                      1   3    5   7
             */But i hope the new code can handle tree like:
             *                             4
             *                           /   | \
             *                          /     |   \
             *          t =            2     8   6
             *                        / |  \    |    /| \
             *                      1 11  3 9   5 10  7
             */Thanks

    sunnymanman wrote:
    Dear Friends,
    I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ...The answer is interfaces.
    What do all trees have in common? And what do all nodes in trees have in common?
    At least these things:
    interface Tree<T> {
        Node<T> getRoot();
    interface Node<T> {
        T getData();
        List<Node<T>> getChildren();
    }Now write concrete classes implementing these interfaces. Let's start with a binary tree (nodes should have comparable items) and an n-tree:
    class BinaryTree<T extends Comparable<T>> implements Tree<T> {
        protected BTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class BTNode<T> implements Node<T> {
        private T data;
        private Node<T> left, right;
        public List<Node<T>> getChildren() {
            List<Node<T>> children = new ArrayList<Node<T>>();
            children.add(left);
            children.add(right);
            return children;
        public T getData() {
            return data;
    class NTree<T> implements Tree<T> {
        private NTNode<T> root;
        public Node<T> getRoot() {
            return root;
    class NTNode<T> implements Node<T> {
        private T data;
        private List<Node<T>> children;
        public List<Node<T>> getChildren() {
            return children;
        public T getData() {
            return data;
    }Now with these classes, you can wite a more generic traversal class. Of course, every traversal class (breath first, depth first) will also have something in common: they return a "path" of nodes (if the 'goal' node/data is found). So, you can write an interface like this:
    interface Traverser<T> {
        List<Node<T>> traverse(T goal, Tree<T> tree);
    }And finally write an implementation for it:
    class BreathFirst<T> implements Traverser<T> {
        public List<Node<T>> traverse(T goal, Tree<T> tree) {
            Node<T> start = tree.getRoot();
            List<Node<T>> children = start.getChildren();
            // your algorithm here
            return null; // return your traversal
    }... which can be used to traverse any tree! Here's a small demo of how to use it:
    public class Test {
        public static void main(String[] args) {
            Tree<Integer> binTree = new BinaryTree<Integer>();
            // populate your binTree
            Tree<Integer> nTree = new NTree<Integer>();
            // populate your nTree
            Traverser<Integer> bfTraverser = new BreathFirst<Integer>();
            // Look for integer 6 in binTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, binTree));
            // Look for integer 6 in nTree
            System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, nTree));
    }Good luck!

  • How we know the selected node in a Tree object in a form?

    In a TREE object in forms, how can we know the current selected node by clicking a push button.
    lets say , there are 10 nodes in my tree, and 5th one i selected. But i want to store the selected node in a variable, when i click a button.
    please help
    thanks

    Hello
    I've just notice what might be a bug in Oracle forms because when I have the when-tree-node-selected trigger present for the tree (It does not matter if it executes null or some code), the code in option 1 works fine on a when-button-pressed trigger on a button item. This is what I had done to give you a reply.
    My second option will work because you're populating a parameter with when-tree-node-selected trigger which is then readable form anywhere else in the form. All you add is a check on when-button-pressed. Also for bug handling you need to consider setting the value to null when deselecting. I have this option working currently in one of my applications.
    DECLARE
         num_selected NUMBER;
         htree ITEM;
    curren_node FTREE.NODE;
    BEGIN
    htree := find_item('tree.form_list');
    num_selected := ftree.get_tree_property(htree,ftree.selection_count);
    for j in 1..num_selected
    LOOP
    curren_node := ftree.get_tree_selection(htree,j);
    message('hello :'||ftree.Get_Tree_Node_Property(htree,curren_node,ftree.node_value),acknowledge);
    end loop;
    END;     
    cheers
    Q

  • How to design  databse for binary tree

    kindly help in desiging databse for binary tree and also to retrive data from database.

    Since you're not asking about Java, you'll probably get more responses by posting this in a database forum.

  • How to next consecutive node in binary tree and insert in sql server

    i need to find next node in this tree and insert in sql server ...
    dilip kumar

    It depends you data structure. How do you store this tree structure in the database? What's the database design? BTW, you can see this article which include a related sample :
    Custom Sort in Acyclic Digraph
    T-SQL e-book by TechNet Wiki Community
    My Blog
    My Articles

  • Searching for a certain  binary tree from another tree........

    I have been struggling for a tree search problem for a good while. Now I decide to ask you experts for a better solution :-).
    Given a binary tree A. We know that every Node of A has two pointers. Leaves of A can be tested by if(node.right = =node). Namely, The right pointer of every leaf node points to itself. (The left pointer points to the node sits on the left side of the leaf in the same depth. and the leafmost node points to the root. I do no think this information is important, am i right?).
    Tree B has a similar structure.
    The node used for both A and B.
    Node{
    Node left;
    Node right;
    My question is how to test if tree B is a subtree of A and if it is, returns the node in A that corresponds to the root of B. otherwise, return null.
    So, the method should look like:
    public Node search(Node rootOfA, Node rootOfB){
    I know a simple recursive fuction can do the job. The question is all about the effciency....
    I am wonderring if this is some kind of well-researched problem and if there has been a classical solution.
    Anyone knows of that? Any friend can give a sound solution?
    Thank you all in advance.
    Jason
    Message was edited by:
    since81

    I'm not too sure if this would help but there goes.
    I think a recursive function will be the easiest to implement (but not the most efficient). In terms of recursive function if you really want to add performance. You could implement your own stack and replace the recursive function with the use of this stack (since really the benefit of recursive function is that it manages its own stack). A non-recursive function with customized well implemented stack will be much more efficient but your code will become more ugly too (due to so many things to keep track of).
    Is tree B a separate instance of the binary tree? If yes then how can Tree B be a subset/subtree of tree A (since they are two separate "trees" or instances of the binary tree). If you wish to compare the data /object reference of Tree B's root node to that of Tree A's then the above method would be the most efficient according to my knowledge. You might have to use a Queue but I doubt it. Stack should be able to replace your recursive function to a better more efficient subroutine but you will have to manage using your own stack (as mentioned above). Your stack will behave similar to the recursive stack to keep track of the child/descendant/parent/root node and any other references that you may use otherwise.
    :)

  • Non binary trees in java

    Hi guys i am used in creating binary trees ,tell me how do we create non binary trees in java.

    public class Node {
      private final Object payload;
      private final Set<Node> children;
      public Node(Object payload) {
        this.payload = payload;
        children = new HashSet<Node>();
      // now add methods to add/remove children, a method to do something with the payload (say,
      // a protected method that passes the payload to a method specified by some kind of interface),
      // and methods to recurse over children.
    }Actually rather than using Object probably should have generic-ized the class, but whatever.

Maybe you are looking for

  • Embedding video in email

    Does anyone know whether it's possible to embed a video clip in an email? If so, how? TIA, Pete

  • F4200 All-in-One scanner suddenly not working

    I have been very happy with my HP Deskjet F4200 All-in-One printer/scanner. Suddenly today the scanner refuses to wrok. I get a report: ERROR The scan cannot be performed because another program has control of the HP imaging device.  Try the followin

  • Excise(serious issue)

    hi friends..         when excise was changed from 10% to 8%, i changed the conditions records for all tax code with JMOP conditions type from 10% to 8% directly in t-code FV12 and saved.       My issue is before changing BED was calculating properly

  • How do I get rid of this message

    How do I get rid of this message on start up (after up grading to leopard, Powerbook G4)? The application "HotSync Manager" could not be launched because of a shared library error: "<HotSync Manager><HotSync Manager><HotSyncLib.PPC>" Not sure how to

  • Which command we use to check  root privileged users in solaris

    Hi, please tell me ,if i want to check the number of people using super user privilege in the sun solaris server .how we can find that ? ,is there any command to find that ? please reply me boby