-4
私がツリーを検索するために使用した方法は、再帰によるものです。私は再帰から壊れてプログラムを正常な流れにすることができるかどうか疑問に思っていました。 だから、基本的に私は、スタックを追跡することなく再帰から逃れる方法はありますか? 誰も私に何か他の方法を提案できないのですか?DFS検索(ツリー)コードに問題があります。再帰を壊すには?
BinaryTreeクラス
class BinaryTree
{
public:
template <class T>
class Node {
public:
Node(T item) {
this->item = item;
this->left = nullptr;
this->right = nullptr;
}
Node* left;
Node* right;
T item;
};
BinaryTree();
template<class T>
void DFS(Node<T> *N);
private:
Node<char>* root;
};
BinaryTree::BinaryTree()
{
this->root = new Node<char>('A');
this->root->left = new Node<char>('B');
this->root->right = new Node<char>('C');
this->root->left->left = new Node<char>('D');
this->root->left->right = new Node<char>('E');
this->root->right->left = new Node<char>('F');
this->root->right->right = new Node<char>('G');
this->DFS(root);
}
template <class T>
void BinaryTree::DFS(Node<T>* N) {
if(N == nullptr)
return;
cout << N->item << endl;
if(N->item == 'E') {
cout << "found\n";
//Break from recursion;
}
DFS(N->left);
DFS(N->right);
}
生成される出力
A
B
D
E
found
C
F
G
出力に必要な
A
B
D
E
found
「トラブル」とは何ですか?あなたは具体的な問題を抱えていますか?同じ結果を生み出すためにコードを書き直す方法を求めていますか? –
アイテムが見つかった後、プログラムが再帰を中断させたい。 –
リターン;あなたがコメント行に書いておきたいものです – lars