tree - Traverse PreOrder in BinarySearchTree (Java) -
i need help. runned full code via junit still errors. think because of traverse code.
the purpose of traverse code create linkedlist in in preorder.
for example: junit says wrong
assertarrayequals( new integer[]{2, 14, 26, 86, 122, 134, 182}, arrays.copyof(tree.traversepreorder(), tree.getsize(), integer[].class));
@override public object[] traversepreorder() { binarytreenode<t> x = root; linkedlist<object> y = new linkedlist<object>(); if (x == null) { return null; } else { y.add(x.value); y.add(travpreord(x.getleft())); y.add(travpreord(x.getright())); } return y.toarray(); } public linkedlist<object> travpreord(binarytreenode<t> x) { binarytreenode<t> tmp = x; linkedlist<object> space = new linkedlist<object>(); if (x == null) { return null; } else { space.add(tmp.getvalue()); space.add(travpreord(x.getleft())); space.add(travpreord(x.getright())); } return space; }
you have big problem since add results of travpreord
, list<object>
or null
if node doesn't exist.
the best solution these cases maintain overridden method non-recursive , overload method uses recursion , has argument receives container has add data:
public list<object> travpreord(binarytreenode<t> x) { binarytreenode<t> tmp = x; list<t> space = new linkedlist<t>(); travpreord(x, space); return space; } private void travpreord(binarytreenode<t> x, list<t> space) { if (x == null) { return; } space.add(tmp.getvalue()); travpreord(x.getleft(), space); travpreord(x.getright(), space); }
Comments
Post a Comment