//定義樹結構
struct Tree{
int data;
Tree *left;
Tree *right;
Tree(){
this->data = 0;
this->left = nullptr;
this->right = nullptr;
}
};測試
//遞歸先序遍歷
void visit_recursive1(Tree *tree){
if(tree){
printf("data--->%d\n",tree->data);
if(tree->left){
visit_recursive1(tree->left);
}
if(tree->right){
visit_recursive1(tree->right);
}
}
}this
//遞歸中序遍歷
void visit_recursive2(Tree *tree){
if(tree){
if(tree->left){
visit_recursive2(tree->left);
}
printf("data--->%d\n",tree->data);
if(tree->right){
visit_recursive2(tree->right);
}
}
}遞歸
//非遞歸先序遍歷
void visit1(Tree *tree){
stack<Tree*> m_stack;
Tree *cur = tree;
while (cur) {
printf("data--->%d\n",cur->data);
m_stack.push(cur);
cur = cur->left;
while(!cur && !m_stack.empty()){
cur = m_stack.top()->right;
m_stack.pop();
}
}
}it
//測試
int main(int argc, const char * argv[]) {
Tree head;
head.data = 1;
Tree tree2;
tree2.data = 2;
Tree tree3;
tree3.data = 3;
Tree tree4;
tree4.data = 4;
Tree tree5;
tree5.data = 5;
Tree tree6;
tree6.data = 6;
head.left = &tree2;
head.right = &tree3;
tree2.left = &tree4;
tree2.right = &tree5;
tree3.left = &tree6;
visit_recursive1(&head);
visit_recursive2(&head);
visit1(&head);
return 0;
}遍歷