我创建了一个{2,5,3,4,9,1,7,...,100}
位的二叉搜索树。
如何将其保存为preorder
?
感谢
编辑:考虑我有{ 3,7,1,2}
并使用这些数字制作binary search tree
,我想将此树保存为preorder which is {3,1,2,7}
答案 0 :(得分:5)
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);
}
}
答案 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