我用来搜索树的方式是通过递归。
我想知道我是否可以从递归中脱离并达到程序的正常流程。
因此,我基本上要说的是,有没有办法从递归中折断而无需追踪堆栈?
如果没有,任何人都能以其他方式建议我?
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 << "foundn";
//Break from recursion;
}
DFS(N->left);
DFS(N->right);
}
输出生成
A
B
D
E
found
C
F
G
输出需要
A
B
D
E
found
我想到的最简单解决方案:
template <class T>
bool BinaryTree::DFS(Node<T>* N) {
if(N == nullptr)
return false;
cout << N->item << endl;
if( N->item == 'E') {
cout << "foundn";
return true;
}
if(DFS(N->left))
return true;
if(DFS(N->right))
return true;
return false;
}
但是,您需要更改类声明中的返回类型。