1.从根结点开始,一直访问左孩子,直到NULL,将其全部压栈.
2.打印栈顶结点,做出栈操作,将r指向右孩子.
重复1.2.直到结束.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include<cstdio> #include<cstdlib> #include<cstring> #include<stack> #include<queue> using namespace std;
typedef int DATA_TYPE;
typedef struct node { DATA_TYPE data; node *lch, *rch; node() { data = 0; lch = rch = 0; } } Node;
Node nodeList[100];
void print(Node *r) { if(r) { print(r->lch); printf("%d", r->data); print(r->rch); } }
Node *buildTree(DATA_TYPE dataArray[], int len) { for(int i=1; i<len; i++) { nodeList[i].data = dataArray[i]; if(i%2) { nodeList[i/2].rch = &nodeList[i]; } else { nodeList[i/2].lch = &nodeList[i]; } } return &nodeList[1]; }
void inOrderTraversal(Node *r) { Node *p; stack<Node*> s; while(!s.empty() || r) { while(r) { s.push(r); r=r->lch; } p = s.top(); s.pop(); printf("%d", p->data); r=p->rch; } }
int main() { DATA_TYPE dataArray[] = {0,1,2,3,4,5,6,7}; Node *root = buildTree(dataArray, sizeof(dataArray)/sizeof(DATA_TYPE)); inOrderTraversal(root); return 0; }
|