将树保存为预订

时间:2010-12-27 14:45:23

标签: java binary-tree

我创建了一个{2,5,3,4,9,1,7,...,100}位的二叉搜索树。

如何将其保存为preorder? 感谢

编辑:考虑我有{ 3,7,1,2}并使用这些数字制作binary search tree,我想将此树保存为preorder which is {3,1,2,7}

2 个答案:

答案 0 :(得分:5)

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

完整的article on binary trees and PreOrder traversals

答案 1 :(得分:0)

以下算法打印所有节点,每行一个, 二叉树v

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 
}

来源:here