// Return all keys in this OrderedMap as an ArrayList of Ks.
// The first element in the ArrayList must be key that precedes all other keys.
// The last element must be key that follows all other keys.
public ArrayList<K> keysAsList()
that is actually the method that I have to make, so will the level-order work?
That requirement is incomplete, because it only constrains the first and
last elements. I would think that returning a list where the elements
are totally ordered would be best. This is not required here, but seems
like commonsense to me., since the whole point to a BST is its ordering.
You should already know how to traverse a BST to visit the nodes in order:
http://en.wikipedia.org/wiki/Binary_search_tree
Yeah it's already a BST so I won't have to order it again. My instructor says to use the in-order method. But then if I use the in-order method wouldn't the first value of the arraylist be a leaf instead of the value in the root?
public ArrayList keysAsList() {
ArrayList result = new ArrayList();
keysAsList(root);
return result;
}
public void keysAsList(TreeNode t){
keysAsList(t.left);
result.add(t.data);
keysAsList(t.right);
}
will this work?
> My instructor says to use the in-order method.
> But then if I use the in-order method wouldn't the
> first value of the arraylist be a leaf instead of the
> value in the root?
I think you are confused about what a BST looks like. Here is the example
from the Wikipedia article:
[url #" style="display: block; background-image: url('http://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Binary_search_tree.svg/150px-Binary_search_tree.svg.png'); width: 150px; height: 125px] [/url]
In a BST, the root does not necessarily contain the least element. Instead, the invariant is that for each node, its value is greater than all the values
in its left subtree and less than all the values in its right subtree.
A breadth-first traversal of this tree yields: [8, 3, 10, 1, 6, 14, 4, 7, 13]
An inorder traversal yields: [1, 3, 4, 6, 7, 8, 10, 13, 14]
yeah so I think based on the assignment that I have, which is :
The first element in the ArrayList must be key that precedes all other keys.
The last element must be key that follows all other keys.
the in order would be right, correct? Because on the example above 1 preceedes all other values?
My instructor also says that the root value will be somewhere around the size of the arraylist/2
And I don't have an access to a compiler, I am at the library now
>
> I think you are confused about what a BST looks like.
> Here is the example
> from the Wikipedia article:
>
Hmmm...as far as I can recall that is the first time that I have ever seen the ability to be able to post pictures used in a way to help clarify an actual technical discussion.