簡體   English   中英

二叉樹:有序迭代器:Java

[英]Binary Trees: In-order Iterator: Java

我將如何編寫迭代器以“有序”方式遍歷二叉樹的每個值? 我應該使用堆棧。 BinaryNode是一個簡單的節點類,帶有指向“左”和“右”節點的指針。 這是我到目前為止的內容:

class InOrderIterator implements Iterator<T> {

    private Stack<BinaryNode> stack;

    public InOrderIterator(BinarySearchTree<T>.BinaryNode root) {
        stack = new Stack<BinaryNode>();
        stack.push(root);
    }

    @Override
    public boolean hasNext() {
        while (!this.stack.isEmpty() && stack.peek() == NULL_NODE)
            this.stack.pop();
        return !this.stack.isEmpty();
    }

    @Override
    public T next() {
        //TODO

        if (!this.hasNext())
            throw new NoSuchElementException("No more nodes in tree!");

        BinaryNode current = this.stack.pop();
        BinaryNode output = null;

        while(current != NULL_NODE){
            this.stack.push(current);
            current = current.left;
        }

        if(current == NULL_NODE){
            if(!this.stack.isEmpty()){
                output = this.stack.pop();
                return output.data;
            }
        }
        return null;
    }
}

我已經掌握了基本算法,但是似乎無法將其轉換為Java代碼。

考慮不變式。 您有一堆節點。 節點在堆棧上意味着什么?

我可能建議:堆棧上的一個節點代表一個“半樹”,一個節點及其整個右子樹,並且堆棧保存所有半樹,這些半樹共同構成了所有未從next()返回的節點。然而。

這些半樹應按什么順序推入堆棧? 回答該問題將為您提供不變的條件,即在代碼運行時將保留的屬性。

令自己滿意的是,您的不變式意味着堆棧的頂部必須是next()將要返回的next。 當您彈出它返回它時,您將不得不在返回之前以某種方式處理其正確的子樹。 從您的不變性來看,如何做到這一點應該很明顯。

如果您不自覺和明確地考慮變量的含義和不變量是什么,那么您的編碼工作將是無方向的。 您將四處亂竄,編寫意大利面條代碼。 但是,一旦完成,代碼將自行編寫。

public class BinaryTreeNode {
    private int element; //element stored at this node

    private BinaryTreeNode left, right; 

    public BinaryTreeNode() {  }

    public BinaryTreeNode(int element) {
        setElement(element);
        setLeft(null);
        setRight(null);
    }

    //returns the elements stored at this position
    public int element() {
        return element;
    }

    //sets the elements  stored at this position
    public void setElement(int e) {
        element = e;
    }

    //return the left child of this position
    public BinaryTreeNode getLeft() {
        return    left;
    }

    //set the left chid of this position
    public void  setLeft(BinaryTreeNode l) {
        left = l;
    }

    //return the right child of this position
    public BinaryTreeNode getRight() {
        return    right;
    }

    //sets the right child of this position
    public void  setRight(BinaryTreeNode r) {
        right = r;
    }      

}

public class TestBTN {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        BinaryTreeNode root = null, right, left, node = null;

        int arrayInt[] = {25, 20, 7, 13, 33, 50, 45, 17, 30, 55};

        for (int i = 0; i < arrayInt.length; i++) {
            if (root == null) {
                root = node = new BinaryTreeNode(arrayInt[0]);
            }//endIf
            else {
                node = new BinaryTreeNode(arrayInt[i]);
                BinaryTreeNode s, p;
                p = s = root;
                while (s != null) {
                    p = s;
                    if (node.element() > s.element()) {
                        s = s.getRight();
                    } else {
                        s = s.getLeft();
                    }
                }//endWhile
                if (node.element() > p.element()) {
                    p.setRight(node);
                } else {
                    p.setLeft(node);
                }
            }//emdElse
        }//endFor

        //printing
        //Print(root);
        //PostOrder(root);
        //PreOrder(root);
        InOrder(root);
        //System.out.println("\nBinaryTreeNode");

    }//endMain

    private static void Print(BinaryTreeNode node) {
        if (node != null) {
            System.out.print(node.element() + " ");
            Print(node.getLeft());
            Print(node.getRight());
        }//endIf
    }//endPrint

    static void PostOrder(BinaryTreeNode ptr) {
        if(ptr != null) {
            PostOrder(ptr.getLeft());
            PostOrder(ptr.getRight());
            System.out.print(ptr.element()+" ");
        }//endIf
    }//endPost

    static void PreOrder(BinaryTreeNode ptr) {
        if(ptr != null) {
            System.out.print(ptr.element()+" ");
            PreOrder(ptr.getLeft());
            PreOrder(ptr.getRight());

        }
    }        

    static void InOrder(BinaryTreeNode ptr) {
        if(ptr != null) {
            InOrder(ptr.getLeft());
            System.out.print(ptr.element()+" ");
            InOrder(ptr.getRight());
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM