C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

再帰を伴わない順序ツリートラバーサルのためのC++プログラム


二分木が順番にトラバースされる場合、最初に左側のサブツリーにアクセスし、次にルートにアクセスし、次に右側のサブツリーにアクセスします。 in_orderトラバーサルで昇順でキーを出力します。これは、再帰のない順序付きツリートラバーサル用のC++プログラムです。

アルゴリズム

Begin  
   Function inOrder():
      Declare a stack s.
      Declare the current node as root.
      While current node is not null and stack is not empty do
         While current node is not null do
            Push the current node on the top of the stack
            Make the left child node as current node
         Point the current node at the top of the stack.
         Pop the top most node from the stack
         Print the current node.
         Make the right node as current node.  
      Insert some elements at root, left node and right node in stack.
      Call the inOrder() function to traverse the tree. 
End.

サンプルコード

#include<bits/stdc++.h>
using namespace std;

struct n {
   int d;
   struct n* l;
   struct n* r;
   n (int d) {
      this->d = d;
      l = r = NULL;
   }
};

void inOrder(struct n *root) {
   stack<n *> s;
   n *current = root;

   while (current != NULL || s.empty() == false) {
      while (current != NULL) {
         s.push(current);
         current = current->l;
      }

      current = s.top();
      s.pop();

      cout << current->d << " ";
      current = current->r;
   }
}

int main() {
   struct n *root = new n(7);

   root->l = new n(6);
   root->r = new n(2);
   root->l->l = new n(1);
   root->l->r = new n(9);

   inOrder(root);
   return 0;
}

出力

1 6 9 7 2

  1. 二分法のためのC++プログラム

    0であり、関数f(x)はaとbの間にある必要があります。つまりf(x)=[a、b ]。タスクは、二分法を使用して、関数f(x)の区間aとbの間にあるルートの値を見つけることです。 二分法とは何ですか? 二分法は、「a」と「b」で定義された指定された制限内の関数f(x)の根の値を見つけるために使用されます。関数の根は、f(a)=0となるような値aとして定義できます。 例 Quadratic equation F(x) =  - 8 This equation is equals to 0 when the value of x will be 2 i.e.  - 8 =

  2. 与えられた二分木の順序の再帰的走査を実行するC++プログラム

    ツリートラバーサルは、グラフトラバーサルの一種です。これには、ツリー内の各ノードを1回だけチェックまたは印刷することが含まれます。二分探索木の順序どおりの走査には、ツリー内の各ノードを順番に(左、根、右)訪問することが含まれます。 二分木のインオーダートラバーサルの例は次のとおりです。 二分木は次のように与えられます。 インオーダートラバーサルは次のとおりです:1 4 5 6 8 順序どおりの再帰的走査を実行するプログラムは次のとおりです。 例 #include<iostream> using namespace std; struct node {