二叉树中序遍历递归与非递归算法

 

#include <iostream>
#include <stack>

using namespace std;

struct Bintree {
  Bintree *left;
  Bintree *right;
  Bintree *parent;
  int data;
	
  Bintree():left(NULL),right(NULL),parent(NULL),data(0){}
};

int mycount = 3;
int i = 0;
Bintree *create_bintree()
{
  p = new Bintree();
  p->data = ++i;
  if (--mycount >= 0) {
    p->left = create_bintree(p->left);
    p->right = create_bintree(p->right);
  }
  return p;
}

Bintree *create_bintree1(int depth)
{
  p = new Bintree();
  p->data = ++i;
  if (depth) {
    p->left = create_bintree1(p->left, depth-1);
    p->right = create_bintree1(p->right, depth-1);
  }
  return p;
}

Bintree *create_bintree2(int parent, int depth)
{
  p = new Bintree();
  p->data = parent;
  if (depth) {
    p->left = create_bintree2(p->left, 2*parent, depth-1);
    p->right = create_bintree2(p->right, 2*parent+1, depth-1);
    p->left->parent = p->right->parent = p;
  }
  return p;
}

void ldr(Bintree *p)  //递归
{
  if (!p) return;
  ldr(p->left);
  cout << p->data << " ";
  ldr(p->right);
}

void nonrecLdr(Bintree *p)  //基于栈的非递归
{
  if (!p) return;
  stack<Bintree *> s;

  while(1) {
    while (p) {
      s.push(p);
      p = p->left;
    }
    if (s.empty()) {
      cout << endl;
      return;
    }
    p = s.top();
    s.pop();
    cout << p->data << " ";
    p = p->right; 
  }
}

void nonrecNonstackLdr(Bintree *p) //用了父结点指针的无额外空间消耗的非递归
{
  if (!p) return;
  while (p) {
    while (p->left) {
      p = p->left;
    }
    cout << p->data << " ";
    while (p) {
      if (p->right) {
	p = p->right;
	break;
      } else {
	while (p->parent && p->parent->right == p) p = p->parent;
	p = p->parent;
	if (p) cout << p->data << " ";
      }
    }
  }
  cout << endl;
}

int main()
{
  Bintree *root;
  root = create_bintree2(root, 1, 2);
  ldr(root);
  cout << endl;
  nonrecLdr(root);
  nonrecNonstackLdr(root);
  return 0;
}

你可能感兴趣的:(二叉树)