How to create a Binary Tree from a General Tree?
Posted
by mno4k
on Stack Overflow
See other posts from Stack Overflow
or by mno4k
Published on 2010-06-10T16:10:26Z
Indexed on
2010/06/10
16:12 UTC
Read the original article
Hit count: 360
I have to solve the following constructor for a BinaryTree class in java:
BinaryTree(GeneralTree<T> aTree)
This method should create a BinaryTree (bt) from a General Tree (gt) as follows:
Every Vertex from gt will be represented as a leaf in bt.
- If gt is a leaf, then bt will be a leaf with the same value as gt
- If gt is not a leaf, then bt will be constructed as an empty root, a left subTree (lt) and a right subTree (lr). Lt is a stric binary tree created from the oldest subtree of gt (the left-most subtree) and lr is a stric binary tree created from gt without its left-most subtree.
The frist part is trivial enough, but the second one is giving me some trouble. I've gotten this far:
public BinaryTree(GeneralTree<T> aTree){
if (aTree.isLeaf()){
root= new BinaryNode<T>(aTree.getRootData());
}else{
root= new BinaryNode<T>(null); // empty root
LinkedList<GeneralTree<T>> childs = aTree.getChilds(); // Childs of the GT are implemented as a LinkedList of SubTrees
child.begin(); //start iteration trough list
BinaryTree<T> lt = new BinaryTree<T>(childs.element(0)); // first element = left-most child
this.addLeftChild(lt);
aTree.DeleteChild(hijos.elemento(0));
BinaryTree<T> lr = new BinaryTree<T>(aTree);
this.addRightChild(lr);
}
}
Is this the right way? If not, can you think of a better way to solve this?
Thank you!
© Stack Overflow or respective owner