先序遍历
class Node{
public:
int data;
Node* left;
Node* right;
Node(int val){
data = val;
}
};
// 先序遍历(递归)
void preOrder(class Node* root){
if(root == NULL){
return;
}
cout<<root->data<< " ";
preOrder(root->left);
preOrder(root->right);
}
//先序遍历(非递归)
void preOrderPlus(class Node* root){
stack<Node*> s;
class Node* curr = NULL;
if(root != NULL){
s.push(root);
}
while(!s.empty()){
curr = s.top();
s.pop();
cout<<curr->data<<" ";
if(curr->right != NULL){
s.push(curr->right);
}
if(curr->left != NULL){
s.push(curr->left);
}
}
}
int main()
{
class Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
preOrder(root);
cout<<"先序遍历(递归)"<<endl;
preOrderPlus(root);
cout<<"先序遍历(非递归)" << endl;
}
?
?
|