开发者

saving a tree as preorder

I have created a binary search tree with {2,5,3,4,9,1,7,...,100} digits.

how can i save it as preorder? thanks

EDIT: Consider I have { 3,7,1,2} and 开发者_JS百科make a binary search tree with these digits and I want to save this tree as preorder which is {3,1,2,7}


Seeh here on literateprograms :

public List<E> toList() {
    List<E> result = new ArrayList<E>();
    treeToList(root, result);
    return result;
}

private void treeToList(Node<E> node, List<E> goal) {
    if (node != null) {
        treeToList(node.left, goal);
        goal.add(node.value);
        treeToList(node.right, goal);
    }
}

A complete article on binary trees and PreOrder traversals.


The following algorithm prints all the nodes, one per line, of the subtree of the node at v in the binary tree bt1.

  public static void preorderPrintLines (BinaryTree bt1, BNode v) { 
          String s = bt1.elementAt(v).toString(); 
                             //the class for the element in the node 
                             //needs to have a toString() method 
          System.out.println (s);   // subtree root element printed

           if (bt1.isInternal(v))   { 
              BNode       p;   
               if (bt1.hasLeft(v)) { 
                                  p  = bt1.left(v); 
                                 preorderPrintLines (bt1, p ); }   
                            //We have just traversed tree of left child 
              if (bt1.hasRight(v)) { 
                                  p  = bt1.right(v); 
                                  preorderPrintLines (bt1, p );  }    
                  //We have just traversed tree of right child 
              } //end if 
}

source : here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜