前序遍历
递归实现
void preOrder(BinTree *root) {
if(root != NULL) {
cout<<root->data<<" ";
preOrder(root->left);
preOrder(root->right);
}
}
非递归实现
BinTree* root;
Stack<BinTree*> s;
BinTree *p = root;
while( p != NULL || !s.empty()){
while(p != NULL) {
cout<<p->data<<" ";
p = p->left;
}
if(!s.empty()) {
p = s.top();
s.pop();
p = p->right;
}
}
中序遍历
递归实现
void midOrder(BinTree *root) {
if(root != NULL) {
preOrder(root->left);
cout<<root->data<<" ";
preOrder(root->right);
}
}
非递归实现
BinTree* root;
Stack<BinTree*> s;
BinTree *p = root;
while( p != NULL || !s.empty()){
while(p != NULL) {
p = p->left;
}
if(!s.empty()) {
p = s.top();
s.pop();
cout<<p->data<<" ";
p = p->right;
}
}
后序遍历
递归实现
void postOrder(BinTree *root) {
if(root != NULL) {
preOrder(root->left);
preOrder(root->right);
cout<<root->data<<" ";
}
}
非递归实现
void postOrder() {
BinTree* root;
Stack<BinTree*> s;
BinTree *cur = root;
BinTree *pre = NULL;
while(!s.empty()){
cur = s.top();
if((cur->left == NULL && cur->right == NULL)
|| pre != NULL &&(pre == cur->left || pre == cur->right)) {
cout<<cur->data<<" ";
s.pop();
pre = cur;
} else {
if(cur->right != NULL) {
s.push(cur->right);
}
if(cur->left != NULL) {
s.push(cur->left);
}
}
}
}