0

スタックを使用せずにO(n)でスレッド化されたバイナリツリーを非再帰的にトラバースする方法(一時変数に一定の余分なスペースを使用できるため、ツリー内の各ノードに訪問フラグを追加できません)。私はそれについて考えるのに良い時間を費やしましたが、ツリーデータがあるメモリ位置をトラバースしない限り、それは実行可能ではないように思えます。複数の配列表現を使用してポインターを実装しているとしましょう。その後、O(n)でツリーをトラバースできますが、他に何か考えていることはありますか?

これは宿題ではありません。宿題についてコメントを書くためのキーボードストロークのエネルギーを節約するためです。

4

2 に答える 2

5

C で次のスレッド化されたツリー表現があるとします。

typedef struct threaded_binary_tree {
    int value;

    // Flag that tells whether right points to a right child or to a next
    // node in inorder.
    bool right_is_child;

    struct threaded_binary_tree *left, *right;
} threaded_binary_tree;

次に、メモリ内でトラバースすると、O(1)次のようになります。

void inorder(threaded_binary_tree *node)
{
    threaded_binary_tree *prev = NULL;

    // Ignore empty trees
    if (node == NULL)
        return;

    // First, go to the leftmost leaf of the tree
    while (node->left != NULL)
        node = node->left;

    while (node != NULL) {
        // Nodes are visited along going upward in the tree
        printf("%d\n", node->value);

        prev = node;
        node = node->right;

        if (prev->right_is_child) {
            // We're descending into tree

            if (node != NULL) {
                // Again, go to the leftmost leaf in this subtree
                while (node->left != NULL)
                    node = node->left;
            }
        }
        // else, we're climbing up in the tree
    }
}

警告: このコードは実行していません。

于 2012-05-06T20:31:00.450 に答える
0

これはJavaで書かれたコードです:

public void inOrder() {
    Node<T> curr = root;
    boolean visited = false; //I haven't come across the node from which I came

    while (curr != null) {
        if (!visited && curr.left != null) { //Go to leftmost node
            curr = curr.left;
        } else {
            System.out.println(curr.head + " ");
            if (curr.right != null) { //I prioritize having childs than "threaded sons"
                curr = curr.right;
                visited = false;
            } else {
                curr = curr.rightThreaded;
                visited = true; //Means that I will come back to a node I've already looped, but now i'll print it, except if i'm at the last node
            }
        }
    }
}

Node は ThreadedBinaryTree の内部クラスです。

private static class Node<T> {
    private T head;
    private Node<T> left;
    private Node<T> right;
    private Node<T> leftThreaded;
    private Node<T> rightThreaded;

    public Node(T head, Node<T> leftThreaded, Node<T> rightThreaded) {
        this.head = head;
        this.leftThreaded = leftThreaded;
        this.rightThreaded = rightThreaded;
    }
}
于 2015-04-12T03:41:59.193 に答える