質問

再帰を使用せずに事前順序トラバーサルを理解することはできますが、順序トラバーサルについては苦労しています。おそらく再帰の内部の仕組みを理解していないため、理解できないようです。

これは私がこれまで試したことです:

def traverseInorder(node):
    lifo = Lifo()
    lifo.push(node)
    while True:
        if node is None:
            break
        if node.left is not None:
            lifo.push(node.left)
            node = node.left
            continue
        prev = node
        while True:
            if node is None:
                break
            print node.value
            prev = node
            node = lifo.pop()
        node = prev
        if node.right is not None:
            lifo.push(node.right)
            node = node.right
        else:
            break

内部の while ループは正しくありません。また、一部の要素は 2 回出力されます。そのノードが以前に出力されたかどうかを確認することでこれを解決できるかもしれませんが、それには別の変数が必要であり、これもまた適切とは思えません。私のどこが間違っているのでしょうか?

私はポストオーダートラバーサルを試したことはありませんが、おそらく似たようなものであり、そこでも同じ概念的な障害に直面することになるでしょう。

御時間ありがとうございます!

追記:の定義 Lifo そして Node:

class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

class Lifo:
    def __init__(self):
        self.lifo = ()
    def push(self, data):
        self.lifo = (data, self.lifo)
    def pop(self):
        if len(self.lifo) == 0:
            return None
        ret, self.lifo = self.lifo
        return ret
役に立ちましたか?

解決

再帰アルゴリズム(擬似コード)でスタート:

traverse(node):
  if node != None do:
    traverse(node.left)
    print node.value
    traverse(node.right)
  endif
あなたは簡単にwhileループにそれを回すことができるように

これは、末尾再帰のクリアケースです。

traverse(node):
  while node != None do:
    traverse(node.left)
    print node.value
    node = node.right
  endwhile

あなたは再帰呼び出しが残っています。どのような再帰呼び出しを行うことは、コンテキストを取得し、それが何をやっていたやり続ける、スタック上に新しいコンテキストをプッシュし始めからコードを実行しています。だから、あなたは、私たちは「最初の実行」の状況(null以外のノード)にいるかどうか、ストレージ用のスタック、および反復ごとに、決定したループを作成したり、「返す」状況(ヌルノード、非空のスタック)及び適切なコード実行

traverse(node):
  stack = []
  while !empty(stack) || node != None do:
    if node != None do: // this is a normal call, recurse
      push(stack,node)
      node = node.left
    else // we are now returning: pop and print the current node
      node = pop(stack)
      print node.value
      node = node.right
    endif
  endwhile

は把握しにくいものは、「リターン」の部分です:あなたはコードをあなたがしているランニングが「入る機能」状況で、または「呼び出しから戻る」状況にあるかどうか、あなたのループで、決定する必要があります、そして、あなたのコード内の非末端再帰を持っているとして、あなたができるだけ多くのケースでif/elseチェーンを持つことになります。

は、この特定の状況では、我々は、状況についての情報を保持するためにノードを使用しています。もう一つの方法は、スタック自体(コンピュータが再帰の場合と同じように)でそれを保存することです。その手法では、コードがより最適であるが、

を従うことが容易に
traverse(node):
  // entry:
  if node == NULL do return
  traverse(node.left)
  // after-left-traversal:
  print node.value
  traverse(node.right)

traverse(node):
   stack = [node,'entry']
   while !empty(stack) do:
     [node,state] = pop(stack)
     switch state: 
       case 'entry': 
         if node == None do: break; // return
         push(stack,[node,'after-left-traversal']) // store return address
         push(stack,[node.left,'entry']) // recursive call
         break;
       case 'after-left-traversal': 
         print node.value;
         // tail call : no return address
         push(stack,[node.right,'entry']) // recursive call
      end
    endwhile 

他のヒント

ここでは簡単なのですで、次の非再帰的なC ++コード..

void inorder (node *n)
{
    stack s;

    while(n){
        s.push(n);
        n=n->left;
    }

    while(!s.empty()){
        node *t=s.pop();
        cout<<t->data;
        t=t->right;

        while(t){
            s.push(t);
            t = t->left;
        }
    }
}
def print_tree_in(root):
    stack = []
    current = root
    while True:
        while current is not None:
            stack.append(current)
            current = current.getLeft();
        if not stack:
            return
        current = stack.pop()
        print current.getValue()
        while current.getRight is None and stack:
            current = stack.pop()
            print current.getValue()
        current = current.getRight();
def traverseInorder(node):
   lifo = Lifo()

  while node is not None:
    if node.left is not None:
       lifo.push(node)
       node = node.left
       continue

   print node.value

   if node.right is not None:
      node = node.right
      continue

   node = lifo.Pop()
   if node is not None :
      print node.value
      node = node.right

PS:私は、Pythonを知らないので、いくつかの構文上の問題があるかもしれません。

これは、C# (.net) でスタックを使用した順序トラバーサルのサンプルです。

(注文後の反復については、以下を参照してください: 再帰を伴わないバイナリ ツリーのポストオーダー トラバース)

public string InOrderIterative()
        {
            List<int> nodes = new List<int>();
            if (null != this._root)
            {
                Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
                var iterativeNode = this._root;
                while(iterativeNode != null)
                {
                    stack.Push(iterativeNode);
                    iterativeNode = iterativeNode.Left;
                }
                while(stack.Count > 0)
                {
                    iterativeNode = stack.Pop();
                    nodes.Add(iterativeNode.Element);
                    if(iterativeNode.Right != null)
                    {
                        stack.Push(iterativeNode.Right);
                        iterativeNode = iterativeNode.Right.Left;
                        while(iterativeNode != null)
                        {
                            stack.Push(iterativeNode);
                            iterativeNode = iterativeNode.Left;
                        }
                    }
                }
            }
            return this.ListToString(nodes);
        }

以下は訪問済みフラグを含むサンプルです。

public string InorderIterative_VisitedFlag()
        {
            List<int> nodes = new List<int>();
            if (null != this._root)
            {
                Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
                BinaryTreeNode iterativeNode = null;
                stack.Push(this._root);
                while(stack.Count > 0)
                {
                    iterativeNode = stack.Pop();
                    if(iterativeNode.visted)
                    {
                        iterativeNode.visted = false;
                        nodes.Add(iterativeNode.Element);
                    }
                    else
                    {
                        iterativeNode.visted = true;
                        if(iterativeNode.Right != null)
                        {
                            stack.Push(iterativeNode.Right);
                        }
                        stack.Push(iterativeNode);
                        if (iterativeNode.Left != null)
                        {
                            stack.Push(iterativeNode.Left);
                        }
                    }
                }
            }
            return this.ListToString(nodes);
        }

binarytreenode、listtostring ユーティリティの定義:

string ListToString(List<int> list)
        {
            string s = string.Join(", ", list);
            return s;
        }


class BinaryTreeNode
    {
        public int Element;
        public BinaryTreeNode Left;
        public BinaryTreeNode Right;        
    }

国家が暗黙のうちに記憶させることができ、

traverse(node) {
   if(!node) return;
   push(stack, node);
   while (!empty(stack)) {
     /*Remember the left nodes in stack*/
     while (node->left) {
        push(stack, node->left);
        node = node->left;
      }

      /*Process the node*/
      printf("%d", node->data);

      /*Do the tail recursion*/
      if(node->right) {
         node = node->right
      } else {
         node = pop(stack); /*New Node will be from previous*/
      }
    }
 }

@Victor、私はスタックに状態をプッシュしようとしているあなたの実装にいくつかの提案を持っています。私はそれが必要であるが表示されません。あなたがスタックから取るすべての要素が既にトラバース残っているので。これに代えてスタックに格納情報を、すべての我々の必要性は、処理されるべき次のノードは、そのスタックからであるかどうかを示すフラグです。以下は、正常に動作します私の実装です。

def intraverse(node):
    stack = []
    leftChecked = False
    while node != None:
        if not leftChecked and node.left != None:
            stack.append(node)
            node = node.left
        else:
            print node.data
            if node.right != None:
                node = node.right
                leftChecked = False
            elif len(stack)>0:
                node = stack.pop()
                leftChecked = True
            else:
                node = None

@Emadpresによって解答のリトル最適化

def in_order_search(node):
    stack = Stack()
    current = node

    while True:
        while current is not None:
            stack.push(current)
            current = current.l_child

        if stack.size() == 0:
            break

        current = stack.pop()
        print(current.data)
        current = current.r_child

これは役立つかもしれない(Java実装)

public void inorderDisplay(Node root) {
    Node current = root;
    LinkedList<Node> stack = new LinkedList<>();
    while (true) {
        if (current != null) {
            stack.push(current);
            current = current.left;
        } else if (!stack.isEmpty()) {
            current = stack.poll();
            System.out.print(current.data + " ");
            current = current.right;
        } else {
            break;
        }
    }
}

再帰することなく、簡単な反復INORDERトラバーサル

'''iterative inorder traversal, O(n) time & O(n) space '''

class Node:
    def __init__(self, value, left = None, right = None):
        self.value = value
        self.left = left
        self.right = right

def inorder_iter(root):

    stack = [root]
    current = root

    while len(stack) > 0:
        if current:
            while current.left:
                stack.append(current.left)
                current = current.left
        popped_node = stack.pop()
        current = None
        if popped_node:
            print popped_node.value
            current = popped_node.right
            stack.append(current)

a = Node('a')
b = Node('b')
c = Node('c')
d = Node('d')

b.right = d
a.left = b
a.right = c

inorder_iter(a)
class Tree:

    def __init__(self, value):
        self.left = None
        self.right = None
        self.value = value

    def insert(self,root,node):
        if root is None:
            root = node
        else:
            if root.value < node.value:
                if root.right is None:
                    root.right = node
                else:
                    self.insert(root.right, node)
            else:
                if root.left is None:
                    root.left = node
                else:
                    self.insert(root.left, node)       

    def inorder(self,tree):
        if tree.left != None:
            self.inorder(tree.left)
        print "value:",tree.value

        if tree.right !=None:
            self.inorder(tree.right)

    def inorderwithoutRecursion(self,tree):
        holdRoot=tree
        temp=holdRoot
        stack=[]
        while temp!=None:
            if temp.left!=None:
                stack.append(temp)
                temp=temp.left
                print "node:left",temp.value

            else:
                if len(stack)>0:
                    temp=stack.pop();
                    temp=temp.right
                    print "node:right",temp.value

ここで@Emadpresを掲載するものに代わるものとして、反復C ++ソリューションです:

void inOrderTraversal(Node *n)
{
    stack<Node *> s;
    s.push(n);
    while (!s.empty()) {
        if (n) {
            n = n->left;
        } else {
            n = s.top(); s.pop();
            cout << n->data << " ";
            n = n->right;
        }
        if (n) s.push(n);
    }
}

ここでINORDERトラバーサルのための反復のPythonのコードがある::

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def inOrder(root):
    current = root
    s = []
    done = 0

    while(not done):
        if current is not None :
            s.append(current)
            current = current.left
        else :
            if (len(s)>0):
                current = s.pop()
                print current.data
                current = current.right
            else :
                done =1

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

inOrder(root)

問題の一部は「prev」変数の使用にあると思います。前のノードを保存する必要はなく、スタック (Lifo) 自体で状態を維持できる必要があります。

から ウィキペディア, 、あなたが目指しているアルゴリズムは次のとおりです。

  1. ルートを訪問します。
  2. 左側のサブツリーをトラバースします
  3. 右側のサブツリーをトラバースする

疑似コード (免責事項: 私は Python を知らないので、以下の Python/C++ スタイルのコードについては申し訳ありません!) では、アルゴリズムは次のようになります。

lifo = Lifo();
lifo.push(rootNode);

while(!lifo.empty())
{
    node = lifo.pop();
    if(node is not None)
    {
        print node.value;
        if(node.right is not None)
        {
            lifo.push(node.right);
        }
        if(node.left is not None)
        {
            lifo.push(node.left);
        }
    }
}

ポストオーダートラバーサルの場合は、左側と右側のサブツリーをスタックにプッシュする順序を単純に交換します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top