Adding to a Linked Complete Binary Tree

Hi all,
I am having major trouble trying to grasp the concept behind adding to a Complete Binary Tree (linked structure). It is part of a much larger assignment that uses a Heap Priority Queue and I am genuinely stuck. I have noticed that there seems to be some sort of strike going on so I wont expect a reply to this.
I understand that Binary Tree's are useful because of their recursive nature, does the process of adding use recursion also. My mind is a mess at the moment so forgive the rambling. My problem exists when I go to add after a right child on a lower level(anything below level 3). I have come to the conclusion that I it is impossible to continue with my adding method and that I should scrap it. Can anyone point anything relevant out to me? I'd appreciate it, thank you.
public class LinkedBT implements CompleteBT
     private BTNode root;          //a reference to the root node
     private BTNode current;          //a reference to the last inserted node
     private BTNode firstNodeInLevel; //a reference to the first node in the level
     private int size;               //keeps track of the size of the BT
     private int currentLevel;
     private int leafCount;
     public LinkedBT()
          root = null;     //instantiate instance variables
          current = null;
          size = 0;
          currentLevel = 0;     //indicates that there are no nodes
          leafCount = 0;
          firstNodeInLevel = null;
     public boolean isEmpty()     
          return (root==null);
     public int size()
          return size;
     public void add(Object obj, int priority)
          BTNode tempNode = new BTNode(obj, priority);
          tempNode.parent = current;                                   //set the parent of the node to current
          if(isEmpty())                                             //if the tree is empty then make a new BTNode and give it the root reference
               root = tempNode;     
               current = root;                                        //make current reference to the root node
               size++;
               currentLevel++;                //increments currentLevel
               return;                          //return control to calling method
          if(current.childrenFull!=true)          //if the current node has available children positions then check left and right and add BTNode appropriately
               if(current.leftChild==null)
                    if(leafCount==0)     //if this is the first node to be added on any given level then.....
                         firstNodeInLevel = tempNode;     //.....store a reference to it for future adding purposes
                    current.leftChild = tempNode;     //adds BTNode to left child
                    leafCount++;
               else
                    current.rightChild = tempNode;          //add BTNode to right child
                    leafCount++;
                    current.childrenFull = true;          //after adding the right child set the childrenFull property true NECESSARY?????
                    if(Math.pow(2, currentLevel)==leafCount)     //IF THIS EVALS TO TRUE THEN THE MAX NUMBER OF LEAVES FOR THAT LEVEL IS REACHED
                         currentLevel++;     //increment the level
                         leafCount = 0;     //reset the leaf count
                         current = firstNodeInLevel;          //change current to the furthest leaf on the left
                    else     //ELSE NEED TO GO BACK UP AND FIND NEXT FEASIBLE POSITION
                         //while(current.parent.rightChild.leftChild.)----------------THIS DOESNT WORK WHEN THE TREE GETS BIGGER
                              //current = current.parent; //set current to next feasible position
          size++;
     public Object getRoot()
          return root;
     public void heapSort()
     private class BTNode
          private Object value;
          private int key;
          private BTNode parent;
          private BTNode leftChild;
          private BTNode rightChild;
          private boolean childrenFull;      //initially false, when both children are occupied then change to true
          private BTNode(Object obj, int priority)     //constructor accepts the value and the priority key
               value = obj;          
               key = priority;
               parent = null;
               leftChild = null;
               rightChild = null;
               childrenFull = false;
          public boolean hasNoChildren()
               return(leftChild==null && rightChild==null);     //returns true if the node has no children
}

Currently working on setting the Linked Servers Security properties. Added the SQLAgent in the" Local server login to remote server login mappings:". The SQLAgent is the only entry in the grid. The SQLAgent has the Remote User and Remote Password
of the AS400. Then below have "Not be made" for "For a login not defined in the lst above, connections will:".
So provided that the SQL Admin only gives SQL Job create, Job Alter and Alter Linked Server to user/groups that he wants to use the linked server the Admin can control access to the linked server.
Any thoughts?

Similar Messages

  • Complete Binary Tree Illustration Question

    Hello I am trying to illustrate the following integers as a complete binary tree:
    20, 12, 17, 36, 25, 49, 52, 65, 42, 35, 71, 43, 54
    I wanted to ask if in inorder to create the complete binary tree, do I need to start in the very middle (52) then half the left and right side and continue this process until complete? eg:
    52
    36 71
    Or do I start from the begining of the array, as below:
    20
    12 36
    17

    Thanks for the answers guys!
    Paul based on what you said, does this then look correct to you or have I got the wrong idea?:
                                                  20
                                      12                        36
                                            17          25              49
                                                              35      42     52
                                                                           43      65
                                                                                54       71

  • 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

  • Infix to Binary Tree

    Hey everyone. I was just wondering if anyone could point me in the right direction. One of my class assignments atm (yeah, I know, don't flame, read on.) is parsing an infix expression (3 + 5 * 4) and turning it into postfix and prefix. Every one has their own way of doing this but I figured I wanted to do it w/ a binary tree.
    Now, my problem lies in the parsing :p I believe I have to do it w/ StringTokenizer but that'd mean adding a lot of priority checks for the operators and the like.
    If anyone can give me some pseudocode or some URLs to read, I'd gladly appreciate it. Please don't post java code, or at least not full programs, as I still have the desire to learn and not be a (complete) slacker.
    Thanks, and sorry if this is the wrong place for this type of post.
    -B

    You could try it with a grammar, these make excellent (not always binary but in this case, binary) trees.
    Parse it, in other words, like so:
    prog --> stmt
    stmt --> E + T || E - T || T
    T --> T * F || T / F || F
    F --> ( E ) || number_literal || -number_literalNote that this in fact makes trinary nodes in some cases, instead of the binary ones you're looking for. I.E.:
      stmt
    /  |  \
    E  +  T
    //instead of
    E     T

  • How to displaying "my favorite Links" as a tree view menu

    Gurus,
    I have a KM iView in portal home page, where users keep adding their favourite links from time to time.  Now I want to display all the links as in tree structure say -
    Content Admin
             |--> Page A
             |--> Page B
    System Admin
             | --> Page C
    Kindly help me out in finding a solution.
    regds,
    Sukanta Rudra

    Krishna,
    Thanks for the reply. I was able to create the tree view.  Now I have two requirements related to this.
    1. How to have them as collapsible menu structure, which gets expanded as and when user wants.
    2. Can we customize it as, Whenever a user add as page in favorites, it will ask for to to put in some folder that is there under my favorites links? I belive it requires some programming customization. Could you guide me, for some solution.
    regds,
    Sukanta Rudra

  • Is there any hope of apple adding a 're-link with media folder'-type function to iTunes?

    Is there any hope of apple adding a 're-link with media folder'-type function to iTunes?
    I have 1000s of broken links after installing the latest version of iTunes and updating some files in my media folder. The location of my itunes library has not changed, and all the files are there (I know because I've just waited several hours for the files to be updated by my ultra-slow computer) - by my logic, there should be some menu option that simply re-synchronises with the media folder, just like itunes would do with an ipod - it can't be that hard can it? The only way I can restore a link is by clicking every song (I have over 28,000) and locating the file in the folder that iTunes claims to use as its media folder - the new version 10 option of then using this location to restore all broken links doesn't work because it only looks in the specific album file, and after a couple of times this dialog box no longer even comes up, so I couldn't ask it to do this even if I wanted to. At the moment the only option I can see is to completely wipe iTunes and re-load all my music from scratch - using my tired and over-worked computer this will realistically take around 15 hours that I don't have, and my computer will melt in the process. I wish I'd never tried to 'tidy up' my iTunes library...
    PLEASE Apple, how hard can it be to have a function that searches for and restores broken links by itself????? I've told you where the music is - just flipping look for it yourself instead of getting me to do it!

    You don't have to re-rip, re-import or re-download all your content. You can clear the iTunes library, either by selecting all in the libary and pressing the Delete key, saying "no" when it asks if you want to remove the files themselves, and then use the Add To Library command, selecting the iTunes Media folder (or iTunes Music folder, as applicable to your situation), and that will add back all your content. It shouldn't take more than a few minutes; if it does, something may be amiss with your hard drive or the library file is corrupted (in which case just delete the library file and re-do the Add To Library command).
    Regards.

  • Binary trees in Java

    Hi there
    Do you have any suggestions about how to implement trees or binary trees in Java?
    As far as I know there are already some libraries for that, but I don't know how to use them. Was trying to get some implementation examples but I'm still very confused.
    How can I use for example:
    removeChild(Tree t)
    addChild(Tree t)
    isLeaf()
    Thanks in advance

    Lulu wrote:
    Hi there
    I have several questions about binary trees
    Let's see, I use TreeMap to create them with the following code:
    TreeMap treeMap = new TreeMap<Integer, String>();
    treeMap.put("first", "Fruit");
    treeMap.put("second","Orange");
    treeMap.put("third", "Banana");
    treeMap.put("fourth", "Apple");You've defined the map to hold integer keys and strings as values, yet you're trying to add string keys and string values to it: that won't work.
    If this is a map how do I define if the data should go to the left or to the right of certain node?That is all done for you. In a TreeMap (using the no-args constructor), you can only store objects that are comparable to each other (so, they must implement the Comparable interface!). So the dirty work of deciding if the entry should be stored, or traversed, into the left or right subtree of a node, is all done behind the scenes.
    Also note that TreeMap is not backed up by a binary tree, or a binary search tree, but by a red-black tree. A red-black tree is a self balancing binary tree structure.
    Should I have dynamical keys so that they increase automatically when adding new data?
    According to a webpage I should use Comparator(), is that to find the data in the tree and retrieve the key?
    ThanksI am not sure what it is you want. I am under the impression that you have to write a binary tree (or a binary search tree) for a course for school/university. Is that correct? If so, then I don't think you're permitted to use a TreeMap, but you'll have to write your own classes.

  • Binary Tree    (insert level by level)

    Hello,
    I'm trying to program a binary tree. It's totally clear for me to insert new (Integer) Values in an ordinary binary tree.
    I simply have to check if the root is equal (--> ready) smaller or larger than the value. I repeat this until I reached a leaf and then I insert a new node.
    BUT:
    My teacher gave me following problem: Inserting values level by level. The first element is the root, the leftson of the root is nuber2 the rightson of the root is number3
    The leftson of root's leftson is number4, the rightson of root's leftson is number 5, the leftson of root's rightson is number 6 and so on.
    I have NO idea how to program that.
    For example: the 23rd element is in the tree: left, right, right, right, whilst the 24th element is right, left, left, left.
    I cannot find a recursive structure, that solves the problem.
    Perhaps YOU can save me from gettin' mad ;o)
    I really hope so.

    It's not quite clear what you mean by level-by-level (at least not to me). The structure of a binary tree depends in the insert order. If you insert 1,5,2,8 the tree will look different to when you insert 1,2,3,4. In the last case the tree actually has degenerated to a linked list (there are only rightsons).
    Now, to minimize the number of levels (if that's what this is about) there's a technique called balancing. In a perfectly balanced binary tree each level is filled before a new level is started. This is quite complicated. Search the net or look in some data structures textbook for balanced binary trees.

  • 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

  • Reconstructing a Binary Tree

    Hi guys ;
    I have a BST class .One of its methods is preorder travesal.
    this method traverse theBinary tree in preorder and prints nodes data to a file.
    Now what i want to do is to be able to construct the binary tree by reading data from this file : keeping in mind the data nodes were saved to this file in preorder.
    Is this a possible thing to do ?
    How can I do this ?
    Is there a better way to save a binary tree to a file and the other way : read from file and construct the tree again?
    Many thanks for helping !

    I'd like to say thanks too.. it really helped me out!
    I used a few minutes (or so ;) to figure out the functions for saving and rebuilding the tree, so I thought I'd post it here, if anyone could use it. Note: this ugly pseudocode might look a little like VB.net-code, which happened completely by accident..
        Private Function SearchForLeaves(ByVal StartNode As Node, ByVal BitString As String) As String
            'Recursive function. If a leaf is found on left or right side of the branch,
            'then print the binary pattern used to get there, else call the function again on the next branch.
            Dim SavedTree As String
            With StartNode
                If .LeftChild.Type = NodeType.Leaf Then
                    Print .leftChild.Value & " " & Bitstring & "0"
                    SavedTree += "!" & .LeftChild.Value
                Else
                    SearchForLeaves(.LeftChild, BitString & "0")
                End If
                If .RightChild.Type = NodeType.Leaf Then
                    Print .leftChild.Value & " " & Bitstring & "1"
                    SavedTree += "!" & .RightChild.Value
                Else
                    SearchForLeaves(.RightChild, BitString & "1")
                End If
                SavedTree += "?"
            End With
            Return SavedTree
        End Function
        Private Function RebuildTree(ByVal savedTree As String) As Node
            Dim n As Node
            While Len(savedTree) > 0
                If savedTree.StartsWith("!") Then
                    CropString(savedTree)
                    n = New Node(NodeType.Leaf)
                    n.Value = CropString(savedTree)
                    Stack.Push(n)
                End If
                If savedTree.StartsWith("?") Then
                    CropString(savedTree)
                    n = New Node(NodeType.Branch)
                    n.RightChild = Stack.Pop
                    n.LeftChild = Stack.Pop
                    n.LeftChild.Parent = n
                    n.RightChild.Parent = n
                    Stack.Push(n)
                End If
            End While
            Return Stack.Pop
        End Function
        Private Function CropString(byRef cropMe as String) As String
            Dim L As String
            L = cropMe.Substring(0, 1)
            cropMe = cropMe.Substring(1)
            Return L
        End FunctionCropString just crops off and returns the first character of the string.. I'm going to rewrite this whole thing, but right now I'm just pleased I figured out how to make it work :)
    Cheers!

  • 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;
    }

  • Building a binary tree from a string

    I'm having trouble building a binary tree with shape described in a string.
    00 - means both left and right subtrees are empty;
    01 - means that the left is empty, and the right is not;
    10 - right is empty, left is not
    11 - neither are empty
    public BinaryTree(String s, Iterator it) {
    This constructor is supposed to build the binary tree of the specified shape and fills it with values. THe values come from Iterator it, and are placed into the tree in preorder fashion.
    I have to complete this constructor but I don't really know what to do. I was thinking I could use indexOf somehow. Any help would be greatly appreciated.
    Thanks,
    Mike

    I'd build it like this (this is from the top of my head, so no typo-free-warranties etc.) -- public class Tree {
       private Object data;
       private Tree left= null;
       private Tree right= null;
       private Tree(StringReader sr, Iterator di) {
          char l= (char)sr.read(); // left and right subtree indicators
          char r= (char)sr.read();
          data= di.next(); // set data for this node
          if (l == '1') left= new Tree(sr, di); // build left subtree
          if (r == '1') right= new Tree(sr, di); // build right subtree
       public Tree(String s, Iterator di) {
          this(new StringReader(s), di);
    } Note that the private constructor (the one that does all the work) doesn't handle incorrect strings
    at all, i.e. it'll crash horribly when the string passes contains, say an odd number of characters
    is is simply passing incorrect construction information. Also note that the Iterator must be able
    to iterate over enough elements to be set.
    kind regards,
    Jos

  • Binary tree

    Hi,
    Is there any binary tree class in the collections framework, or anything like that ?
    Thanks

    If all you are going to do is do searching, adding, and removing, it would probably be better to use a HashMap or HashSet. A TreeMap or TreeSet is basically good for maintaining a sorted order. If all you are going to do is search, add, and delete, and never need to get the objects out in sorted order, then the HashMap and HashSet are better because the search, add, and delete are all constant time, O(1), instead of a TreeMap or TreeSet which have O(log N) operations, which is clearly slower.
    I only mention this because you said you wanted good performance, and you can't really get better than O(1).

  • How to display complete menu tree for a particular SAP user in UI5

    Hi Experts,
    I am trying to display menu tree for a particular SAP user on click of button placed in shell content.
    I am referring this link
    Displaying the Complete Menu Tree - User Interface Add-On for SAP NetWeaver - SAP Library
    But I am not getting the exact process.
    Can anyone please provide some help.
    Thanks in advance.

    >
    cranjith kumar wrote:
    > I am displayed a user name and password columns in
    > screen painter.if i will not fill any one of the two fields
    > means then a message will be display.
    > My requirement is if i wont fill the "username field"
    > means then the cursor should not move to the
    > "password"  field (i.e we should not able to enter passwords)
    > and a message should be displayed to indicating that
    > user name is invalid.
    > Kindly send me the coding for this one immediately.....
    How about you immediately try to figure it out for yuorself?  Read the SAP help on screen development and search these forums.  Here's a hint, look at things like FIELD and CHAIN in your PAI...

  • Binary Tree Search

    Hi everyone,
    I have an assignment :Implement a binary search tree class. Include preOrder, inOrder, postOrder traversals, as well as methods to perform insert and search.
    And I did it in the folloiwng but there some problems that I encounter.When I execute the following code, there is an exception occurs. It says that my left BinaryTree is null. So why ???
    Implement a binary search tree class. Include preOrder, inOrder, postOrder traversals, as well as methods to perform insert and search

    Hi,
    I changed the old codes to the below. I think this is orrect logically for binary trees.
    If not, please explain why ??
    import java.util.*;
    class BinaryTree {
         // properties
         ArrayList store;
         BinaryTree left;
         BinaryTree right;
         int root;
         int valuesLeft = 1;      // for adding the left root
         int valuesRight = 1;     // for adding the right root
         // constructors
         // first constructor
         public BinaryTree(BinaryTree left, BinaryTree right){          
              store = new ArrayList();
              root = 12;
              store.add( new Integer(root));  // root value
              this.left = left;
              this.right = right;
         // second constructor
         public BinaryTree(){
              store = new ArrayList();
         // methods
         public void insert(int a){
              if(a < ( (Integer)(store.get(0)) ).intValue()){
                   setLeft(a);
              else{
                   setRight(a);
         public void setLeft(int node){
              if(valuesLeft == 1)
                   root = node;
              (left.store).add(new Integer(node) );
              valuesLeft++;
         public void setRight(int node){
              if(valuesRight == 1)
                   root = node;
              (right.store).add(new Integer(node) );
              valuesRight++;
         public int search(int value){
              if(value == root){
                   return value;
              else if(value < root){
                   return left.search(value);
              else if(value > root)
                   return right.search(value);
              else
                   return -1;     
    //     public String toString(){
         public static void main( String[] args)
              BinaryTree leftTree = new BinaryTree();
              BinaryTree rightTree = new BinaryTree();
              BinaryTree root = new BinaryTree(leftTree, rightTree);
              root.insert(5);     
              root.insert(15);
              root.insert(6);          
              root.insert(3);          
              root.insert(51);
              root.insert(2);     
              root.insert(115);
              root.insert(7);          
              root.insert(33);          
              root.insert(511);               
              root.search(15);     
    }

Maybe you are looking for