163

スタックや再帰を使用せずに、次のモリス順序ツリートラバーサルアルゴリズムを理解するのを手伝ってもらえますか? 私はそれがどのように機能するかを理解しようとしていましたが、それは私を逃れているだけです.

 1. Initialize current as root
 2. While current is not NULL
  If current does not have left child     
   a. Print current’s data
   b. Go to the right, i.e., current = current->right
  Else
   a. In current's left subtree, make current the right child of the rightmost node
   b. Go to this left child, i.e., current = current->left

ツリーが変更され、 がのに変更されることを理解しておりcurrent node、このプロパティを順不同のトラバーサルに使用しています。しかし、それを超えて、私は迷っています。right childmax noderight subtree

編集: この付随する c++ コードが見つかりました。変更後にツリーがどのように復元されるかを理解するのに苦労しました。魔法はelse節にあり、右の葉が変更されるとヒットします。詳細については、コードを参照してください。

/* Function to traverse binary tree without recursion and
   without stack */
void MorrisTraversal(struct tNode *root)
{
  struct tNode *current,*pre;

  if(root == NULL)
     return; 

  current = root;
  while(current != NULL)
  {
    if(current->left == NULL)
    {
      printf(" %d ", current->data);
      current = current->right;
    }
    else
    {
      /* Find the inorder predecessor of current */
      pre = current->left;
      while(pre->right != NULL && pre->right != current)
        pre = pre->right;

      /* Make current as right child of its inorder predecessor */
      if(pre->right == NULL)
      {
        pre->right = current;
        current = current->left;
      }

     // MAGIC OF RESTORING the Tree happens here: 
      /* Revert the changes made in if part to restore the original
        tree i.e., fix the right child of predecssor */
      else
      {
        pre->right = NULL;
        printf(" %d ",current->data);
        current = current->right;
      } /* End of if condition pre->right == NULL */
    } /* End of if condition current->left == NULL*/
  } /* End of while */
}
4

8 に答える 8

189

アルゴリズムを正しく読んでいる場合、これはどのように機能するかの例です。

     X
   /   \
  Y     Z
 / \   / \
A   B C   D

まず、Xはルートなので、 として初期化されcurrentます。Xには左の子があるため、の左のサブツリーのX右端の子になります。これは、順不同のトラバーサルにおける の直前の先行です。は の右の子になり、 に設定されます。ツリーは次のようになります。XXXBcurrentY

    Y
   / \
  A   B
       \
        X
       / \
     (Y)  Z
         / \
        C   D

(Y)上記は、Yおよびそのすべての子を参照しますが、再帰の問題のために省略されています。とにかく重要な部分が記載されています。ツリーが X に戻るリンクを持っているので、トラバーサルは続きます...

 A
  \
   Y
  / \
(A)  B
      \
       X
      / \
    (Y)  Z
        / \
       C   D

次にA、左の子がないため を出力し、前の反復で の右の子にしたにcurrent戻します。次の反復で、Y には両方の子があります。ただし、ループの二重条件により、それ自体に到達すると停止します。これは、左側のサブツリーが既に走査されていることを示しています。したがって、それ自体を出力し、右側のサブツリーである.YAB

Bは、と同じチェック プロセスを経て、左のサブツリーcurrentが走査されたことに気づき、. ツリーの残りの部分は同じパターンに従います。XYZ

再帰は必要ありません。スタックを介したバックトラッキングに頼る代わりに、(サブ) ツリーのルートに戻るリンクが、再帰的な順序のないツリー トラバーサル アルゴリズムでアクセスされるポイントに移動されるためです。左のサブツリーは終了しました。

于 2011-03-31T21:31:46.017 に答える
22

再帰的な順序通りのトラバーサルは :(in-order(left)->key->in-order(right))です。(これは DFS に似ています)

DFS を実行するときは、どこにバックトラックするかを知る必要があります (これが、通常、スタックを保持する理由です)。

バックトラックする必要がある親ノードを通過すると、バックトラックする必要があるノードが見つかり、親ノードへのリンクが更新されます。

バックトラックするときは?これ以上先に進めないとき。先に進めないときは?お子様の留守番の場合。

どこにバックトラックしますか?通知: 後継者へ!

そのため、左側の子パスに沿ってノードをたどるとき、各ステップで先行ノードを現在のノードを指すように設定します。このようにして、前任者は後継者へのリンク (バックトラックへのリンク) を持つことになります。

バックトラックが必要になるまで、できる限り左に進みます。バックトラックする必要がある場合は、現在のノードを出力し、後続ノードへの正しいリンクをたどります。

バックトラックしたばかりの場合 -> 右の子をたどる必要があります (左の子は終わりです)。

バックトラックしたかどうかを確認する方法は? 現在のノードの先行ノードを取得し、(このノードへの) 正しいリンクがあるかどうかを確認します。それがあれば - 私たちはそれに従いました。リンクを削除してツリーを復元します。

左リンクがない場合 => バックトラックせず、左の子に従って続行する必要があります。

これが私の Java コードです (申し訳ありませんが、C++ ではありません)。

public static <T> List<T> traverse(Node<T> bstRoot) {
    Node<T> current = bstRoot;
    List<T> result = new ArrayList<>();
    Node<T> prev = null;
    while (current != null) {
        // 1. we backtracked here. follow the right link as we are done with left sub-tree (we do left, then right)
        if (weBacktrackedTo(current)) {
            assert prev != null;
            // 1.1 clean the backtracking link we created before
            prev.right = null;
            // 1.2 output this node's key (we backtrack from left -> we are finished with left sub-tree. we need to print this node and go to right sub-tree: inOrder(left)->key->inOrder(right)
            result.add(current.key);
            // 1.15 move to the right sub-tree (as we are done with left sub-tree).
            prev = current;
            current = current.right;
        }
        // 2. we are still tracking -> going deep in the left
        else {
            // 15. reached sink (the leftmost element in current subtree) and need to backtrack
            if (needToBacktrack(current)) {
                // 15.1 return the leftmost element as it's the current min
                result.add(current.key);
                // 15.2 backtrack:
                prev = current;
                current = current.right;
            }
            // 4. can go deeper -> go as deep as we can (this is like dfs!)
            else {
                // 4.1 set backtracking link for future use (this is one of parents)
                setBacktrackLinkTo(current);
                // 4.2 go deeper
                prev = current;
                current = current.left;
            }
        }
    }
    return result;
}

private static <T> void setBacktrackLinkTo(Node<T> current) {
    Node<T> predecessor = getPredecessor(current);
    if (predecessor == null) return;
    predecessor.right = current;
}

private static boolean needToBacktrack(Node current) {
    return current.left == null;
}

private static <T> boolean weBacktrackedTo(Node<T> current) {
    Node<T> predecessor = getPredecessor(current);
    if (predecessor == null) return false;
    return predecessor.right == current;
}

private static <T> Node<T> getPredecessor(Node<T> current) {
    // predecessor of current is the rightmost element in left sub-tree
    Node<T> result = current.left;
    if (result == null) return null;
    while(result.right != null
            // this check is for the case when we have already found the predecessor and set the successor of it to point to current (through right link)
            && result.right != current) {
        result = result.right;
    }
    return result;
}
于 2015-02-27T10:54:21.453 に答える
3
public static void morrisInOrder(Node root) {
        Node cur = root;
        Node pre;
        while (cur!=null){
            if (cur.left==null){
                System.out.println(cur.value);      
                cur = cur.right; // move to next right node
            }
            else {  // has a left subtree
                pre = cur.left;
                while (pre.right!=null){  // find rightmost
                    pre = pre.right;
                }
                pre.right = cur;  // put cur after the pre node
                Node temp = cur;  // store cur node
                cur = cur.left;  // move cur to the top of the new tree
                temp.left = null;   // original cur left be null, avoid infinite loops
            }        
        }
    }

このコードは理解しやすいと思います。null を使用して無限ループを回避するだけで、他の魔法を使用する必要はありません。予約注文に簡単に変更できます。

于 2014-10-26T19:25:45.467 に答える
0

Python ソリューション 時間の複雑さ: O(n) 空間の複雑さ: O(1)

優れたモリス順列トラバーサルの説明

class Solution(object):
def inorderTraversal(self, current):
    soln = []
    while(current is not None):    #This Means we have reached Right Most Node i.e end of LDR traversal

        if(current.left is not None):  #If Left Exists traverse Left First
            pre = current.left   #Goal is to find the node which will be just before the current node i.e predecessor of current node, let's say current is D in LDR goal is to find L here
            while(pre.right is not None and pre.right != current ): #Find predecesor here
                pre = pre.right
            if(pre.right is None):  #In this case predecessor is found , now link this predecessor to current so that there is a path and current is not lost
                pre.right = current
                current = current.left
            else:                   #This means we have traverse all nodes left to current so in LDR traversal of L is done
                soln.append(current.val) 
                pre.right = None       #Remove the link tree restored to original here 
                current = current.right
        else:               #In LDR  LD traversal is done move to R  
            soln.append(current.val)
            current = current.right

    return soln
于 2020-04-06T16:02:36.070 に答える