Mercurial > hg > Members > shoshi > TreeCMSv1
changeset 19:a281fb7eaf39
add
author | one |
---|---|
date | Mon, 30 Aug 2010 02:44:50 +0900 |
parents | 423a01ec2d32 |
children | e950264f82d3 |
files | src/treecms/proto/test/PreOrderTreeWalkerRecursive1.java |
diffstat | 1 files changed, 84 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/src/treecms/proto/test/PreOrderTreeWalkerRecursive1.java Mon Aug 30 00:48:50 2010 +0900 +++ b/src/treecms/proto/test/PreOrderTreeWalkerRecursive1.java Mon Aug 30 02:44:50 2010 +0900 @@ -1,5 +1,88 @@ package treecms.proto.test; +import java.util.Iterator; +import java.util.LinkedList; + +import treecms.proto.api.NodeAPI; +import treecms.proto.simple.SimpleNodeAPI; + +public class PreOrderTreeWalkerRecursive1 implements Iterable<NodeAPI> +{ + private NodeAPI m_root; + + public PreOrderTreeWalkerRecursive1(NodeAPI _root) + { + m_root = _root; + } + + @Override + public Iterator<NodeAPI> iterator() + { + return new PreOrderRecursiveIterator(m_root); + } -public class PreOrderTreeWalkerRecursive1 { + class PreOrderRecursiveIterator implements Iterator<NodeAPI> + { + private LinkedList<NodeAPI> nextList; + + public PreOrderRecursiveIterator(NodeAPI _root) + { + nextList = new LinkedList<NodeAPI>(); + getChildren(_root, nextList); + } + + void getChildren(NodeAPI node, LinkedList<NodeAPI>list) { + list.add(node); + for(NodeAPI child : node.getChildList()){ + getChildren(child,list); + } + } + + @Override + public boolean hasNext() + { + return !nextList.isEmpty(); + } + + @Override + public NodeAPI next() + { + return nextList.poll(); + } + + @Override + public void remove() + { + throw new UnsupportedOperationException("cant remove from itrerator"); + } + } + + public LinkedList<NodeAPI> findPath(NodeAPI root, NodeAPI node) { + LinkedList<NodeAPI> list = new LinkedList<NodeAPI>(); + list.addFirst(root); + findPath(root,node,list); + return list; + } + + private boolean findPath(NodeAPI root, NodeAPI node, LinkedList<NodeAPI> list) { + if (root==node) return true; + for(NodeAPI child : node.getChildList()){ + if (findPath(child,node,list)) { + list.addFirst(child); + return true; + } + } + return false; // backtrack + } + + public NodeAPI cloneTree(LinkedList<NodeAPI> path) { + NodeAPI old = path.poll(); + NodeAPI node = new SimpleNodeAPI(old.getTitle()); + node.setClassName(old.getClassName()); + for(NodeAPI child: old.getChildList()) { + if (child==old && !path.isEmpty()) child = cloneTree(path); + node.getChildList().add(child); + } + return node; + } }