`
sillycat
  • 浏览: 2560516 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Interview(4)Sequence Iterator and Tree

 
阅读更多
Interview(4)Sequence Iterator and Tree

Sequence
public interface Sequence extends Vector, List {}

public class SequenceDLNode extends ListDLNode implements Sequence {
    protected void checkRank(int r, int n) throws ExceptionBoundaryViolation {
        if ( r<0 || r >=n){
            throw new ExceptionBoundaryViolation(“Error: r should between 0 -> n”);
        }
    }

    //O(n)
    public Position rank2Pos(int r) throws ExceptionBoundaryViolation {
        DLNode node;
        checkRank(r, getSize());
        if(r <=getSize()/2){ // r is small, from header
            node = header.getNext();
            for( int i = 0;i<r;i++) {
                node = node.getNext();
            }
        }else{
            // r is big, from trailer
            node = trailer.getPrev();
            for (int i = 1;i<getSize() -r; i++) {
                node = node.getPrev();
            }
        }
    }

    public int post2Rank(Position p) throws ExceptionPositionInvalid {
        DLNode node = header.getNext();
        int r = 0;
        while (node != trailer){
            if(node == p) {
                return (r);
            }
            node = node.getNext();
            r++;
        }
        throw new ExceptionPositionInvalid(“error: p is not in sequence”);
    }

    //O(n)
    public Object getAtRank(int r) throws ExceptionBoundaryViolation {
        checkRank(r, getSize());
        return rank2Pos(r).getElem();
    }

    public Object replaceAtRank(int r, Object obj) throws ExceptionBoundaryViolation {
        checkRank(r, getSize());
        return replace(rank2Pos(r), obj);
    }

    public Object insertAtRank(int r, Object obj) throws ExceptionBoundaryViolation {
        checkRank(r, getSize() +1);
        if (getSize() == r ) { insertLast(obj); }
        else { insertBefore(rank2Pos(r), obj);  }
        return obj;
    }

    public Object removeAtRank(int r) throws ExceptionBoundaryViolation {
        checkRank(r, getSize());
        return remove(rank2Pos(r));
    }
}

Iterator
hasNext()
getNext()

java.util.Iterator
java.util.Enumeration   - hasMoreElements() nextElement()

Iterator Implementation
public class IteratorPosition implements Iterator {
    private List list; //
    private Position nextPosition;
   
    public IteratorPosition() { list = null; }
    public IteratorPosition(List l) {
        list = l;
        if(list.isEmpty()){
            nextPosition = null;
        }else{
            nextPosition = list.first();
        }
    }

    public boolean hasNext() { return (nextPosition != null); }
   
    public Object getNext() throws ExceptionNoSuchElement {
        if(!hasNext()) throw new ExceptionNoSuchElement(“Error, no next element");
        Position currentPosition = nextPosition;
        if(currentPosition == list.last()){
            //reach the end
            nextPosition = null;
        }else{
            nextPosition = list.getNext(currentPosition);
        }
        return currentPosition;
    }
}

Tree
Most important data structure, Array and LinkedList
Array is built for lookup the rank, index. Insert remove will be harder.
LinkedList is built for insert/remove, but it will be hard for lookup and iteration.

Array and LinkedList are linear structures.

Tree - concepts - Root, Parent, Node, Child, Edge, Sibling, Degree, Internal Node, External node(Leaf), Path
                          - Ancestor, Descendent, subtree, Empty tree,

Ordered Tree

M Branch Tree

Binary Tree - Proper Binary Tree, Improper Binary Tree

Full Binary Tree
Tree Class - parent, data, firstChild, nextsibling

public class TreeLinkedList implements Tree {
    private Object element; //root node
    private TreeLinkedList parent, firstChild, nextSibling; 

    //single node tree
    public TreeLinkedList(){
        this(null, null, null, null);
    }

    public TreeLinkedList(Object e, TreeLinkedList p, TreeLinkedList c, TreeLinkedList s){
        element = e;
        parent =p;
        firstChild = c;
        nextSibling = s;
    }

    public Object getElem(){ return element; }

    public Object setElement(Object obj) {
        Object bak = element;
        element = obj;
        return bak;
    }

    //return parent node; for root, return null
    public TreeLinkedList getParent(){ return parent; }

    //return first child, if no children, return null
    public TreeLinkedList getFirstChild(){
        return firstChild;
    }
    //return next sibling, return null if no sibling
    public TreeLinkedList getNextSibling(){
        return nextSibling;
    }
    // branches size
    public int getSize(){
        int size = 1; //current node is its own child
        TreeLinkedList subtree = firstChild;
        while (null != subtree) {
            size += subtree.getSize();
            subtree = subtree.getNextSibling();
        }
        return size;
    }

    public int getHeight(){
        int height = -1;
        TreeLinkedList subtree = firstChild;
        while ( null != subtree) {
            height = Math.max(height, subtree.getHeight());  //get the max height of children
            subtree = subtree.getNextSibling();
        }
        return height+1;
    }

    public int getDepth(){
        int depth = 0;
        TreeLinkedList p = parent;
        while(null != p) {
            depth++;
            p = p.getParent();
        }
        return depth;
    }
}

Traversal
Preorder traversal  - Postorder traversal

Method: PreorderTraversal(v)
Inputs:   tree node v
Outputs: all v children preorder traversal

if(null != v){
    for(u = v.getFirstChild(); null != u; u = u.getNextSibling()){
        PreorderTraversal(u);
    }
}

Method: PostorderTraversal(v)
inputs: tree node v
outputs: children of v postorder traversal
{
    if(null != v) {
        for ( u = v.getFirstChild(); null != u; u= u.getNextSibling()) {
            PostorderTraversal(u);
        }
        //visit v after visit all children
    }
}

Traversal by Level
Method: LevelorderTraversal(v)
Inputs: tree node v
Output: Tree node v, traversal by level
{
    if ( null != v) {
        //create a queue
        Q.enqueue(v); //root node in queue
        while (!Q.isEmpty()){
            u = Q.dequeue();
            //visit u
            for( w = u.getFirstChild(); null != w; w= w.nextSibling()) {
                Q.enqueue(w);
            } //for
        } //while
    } //if
}

IteratorTree Class
public class IteratorTree implements Iterator {
    private List list;
    private Position nextPosition;
   
    public IteratorTree() {
        list = null;
    }

    public void elementsPreorderIterator(TreeLinkedList T) {
        if(null == T){  return ; }
        list.insertLast(T); //current node
        TreeLinkedList subtree = T.getFirstChild(); //first child
        while( null != subtree) {
            this.elementsPreorderIterator(subtree);
            subtree = subtree.getNextSibling();
        }
    }

    public void elementsPostorderIterator(TreeLinkedList T){
        if ( null == T) { return ; }
        TreeLinkedList subtree = T.getFirstChild();
        while (null != subtree){
            this.elementsPostorderIterator(subtree);
            subtree = subtree.getNextSibling();
        }
        list.insertLast(T); //visit current/‘root’ after loop
    }

    public void levelTraversalIterator(TreeLinkedList T) {
        if ( null == T) { return ; }
        QueueList queue = new QueueList();
        queue.enqueue(T);
        while(!queue.isEmpty()){
            TreeLinkedList tree = (TreeLinkedList) (queue.dequeue());
            list.insertLast(tree);
            TreeLinkedList subtree = tree.getFirstChild();
            while(null != subtree) {
                queue.enqueue(subtree);
                subtree = subtree.getNextSibling();
            }
        }
    }

    public boolean hasNext() {  return (null != nextPosition); }

    public Object getNext() throws ExceptionNoSuchElement {
        if(!hasNext()) { throw new ExceptionNoSuchElement(“No next position”); }
        Position currentPosition = nextPosition;
        if(currentPosition == list.last()){
            nextPosition = null;
        }else{
            nextPosition = list.getNext(currentPosition);
        }
        return currentPosition.getElem();
    }
}

O(n) for preorder/postorder/by level traversal



References:
http://sillycat.iteye.com/blog/2380702











分享到:
评论

相关推荐

    Bioinformatics. Sequence and Genome Analysis

    这是第二部分Bioinformatics. Sequence and Genome Analysis

    陈越、何钦铭-数据结构作业11:Tree Traversals Again二叉树非递归遍历/栈遍历

    An inorder binary tree traversal ... Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

    Activiti 学习笔记七:连线(SequenceFlow)

    4. 验证与测试:设计完成后,可以使用 Activiti 的API或工作流引擎进行模拟运行,检查流程是否按照预期进行。 四、SequenceFlow的应用场景 1. 逻辑分支:SequenceFlow 可以与决策网关配合,实现基于不同条件的流程...

    NumberSequence

    在Microsoft Dynamics AX(现称为Dynamics 365 Finance and Operations)这款企业资源规划(ERP)软件中,"Number Sequence"功能尤为关键。下面将详细解释如何在AX中使用Number Sequence。 首先,我们需要理解...

    sequence-diagram.zip

    《序列图绘制工具sequence-diagram-js的深度解析与应用》 序列图,作为一种重要的系统建模工具,广泛应用于软件设计和开发中,它清晰地展示了系统内各对象间交互的顺序。sequence-diagram-js是一个基于JavaScript的...

    Transmission Sequence Design and Allocation for Wide Area Ad Hoc Networks

    In this paper we examine the question of designing and allocating transmission sequences to users in a mobile ad hoc network that has no spatially boundary. A basic tenet of the transmission sequence ...

    Oracle sequence 重置(失效恢复)

    WHERE SUBSTR(a.sequence_name, 5, 100) = b.table_name AND b.constraint_type = 'P' ) LOOP SELECT func_getseq(cur.table_name) INTO max1 FROM DUAL; EXECUTE IMMEDIATE 'DROP SEQUENCE ' || cur.sequence_...

    Bioinformatics - Sequence and Genome Analysis - D.W Mount (Cold Spring Laboratory)

    《生物信息学:序列与基因组分析》是D.W Mount所著的一本深入探讨生物信息学领域的经典之作,尤其在蛋白质和DNA序列分析方面提供了详尽的指导。本书不仅覆盖了历史背景、理论基础,还介绍了多种实用的分析工具和技术...

    RNA Sequence, Structure, and Function Computational and Bioinformatic Methods

    RNA序列、结构和功能的计算与生物信息学方法 RNA(核糖核酸)是生物信息学研究中的一个重要对象,它在遗传信息的传递、基因表达的调控以及蛋白质合成等生命过程中扮演着关键角色。随着二代测序技术的飞速发展,RNA...

    sequence等同于序列号

    4. **NO CACHE**:为了防止数据丢失,可以在创建`sequence`时使用`NOCACHE`选项。 #### 六、修改Sequence 要修改`sequence`的属性,需要拥有该`sequence`的所有权或者`ALTER ANY SEQUENCE`权限。可以通过`ALTER ...

    SequenceDiagram-3.0.5.zip

    SequenceDiagram-3.0.5.zip 是一个包含 Sequence Diagram 相关工具或资源的压缩包文件,主要用于绘制序列图,这是UML(统一建模语言)中的一种图表,用于描述对象之间的交互和消息传递顺序。在软件开发过程中,序列...

    list and sequence table .zip_OJ4_Table_list_sequence

    在“list and sequence table .zip_OJ4_Table_list_sequence”这个压缩包中,包含了对这两种数据结构基本操作的实现,主要通过C++语言进行编写,文件名为“顺序表.cpp”和“链表.cpp”。 首先,我们来了解链表。...

    Sequence to Sequence Learning with Neural Networksv论文

    《Sequence to Sequence Learning with Neural Networks》是一篇由Ilya Sutskever, Oriol Vinyals和Quoc V. Le共同撰写的论文,三位作者都来自Google公司。这篇论文在自然语言处理领域有着重要的影响,特别是在序列...

    Genome sequence and analysis of the tuber crop potato

    nature,2011,Genome sequence and analysis of the tuber crop potato.pdf

    Agreement on Target-Bidirectional LSTMs for Sequence-to-Sequence Learning

    memory networks, are extremely appealing for sequence-tosequence learning tasks. Despite their great success, they typically suffer from a fundamental shortcoming: they are prone to generate ...

    Sequence简单介绍.pdf

    4. **更新插入操作**:在进行插入操作时,不再显式指定`IDENTITY`列的值,而是依赖于`Sequence`。 ```sql INSERT INTO Employees (FirstName, LastName) VALUES ('John', 'Doe'); ``` #### 表的迁移 除了`...

    invalid multibyte character sequence 870告警1

    Invalid Multibyte Character Sequence 警告解析 在编程中,特别是在嵌入式系统开发中,我们经常会遇到Invalid Multibyte Character Sequence 警告。这个警告通常来自于编译器,告知我们存在非法的多字节字符序列。...

    《Magnetic Resonance Imaging - Physical Principles and Sequence Design》

    根据提供的信息,《Magnetic Resonance Imaging - Physical Principles and Sequence Design》是一本关于磁共振成像(MRI)的经典教材。本书由Ernst M. Haacke等专家编写,旨在为读者提供深入理解MRI物理原理及序列...

    sequence-to-sequence learning

    机器学习之sequence to sequence learning。(Sequence Generation-----Hung-yi Lee 李宏毅.ppt)

Global site tag (gtag.js) - Google Analytics