[面试] 根据前序和中序重建二叉树,并且中序非递归遍历

#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
#include <iterator>
#include <algorithm>

using namespace std;
class Node {
public :
    int value;
    Node* lchild;
    Node* rchild;
    Node(int v) : value(v), lchild(NULL), rchild(NULL) {}
    ~Node() {
        if(lchild != NULL) delete lchild;
        if(rchild != NULL) delete rchild;
    }
};
Node* build(int *pre, int *mid, int n) {
    if(pre == NULL || mid == NULL || n <= 0) return NULL;
    int rv = pre[0];
    Node* root = new Node(rv);
    int i;
    for(i = 0; i < n && mid[i] != rv; i++);
    int leftL = i;
    if(leftL > 0) root->lchild = build(pre+1, mid, leftL);
    int rightL = n - i - 1;
    if(rightL > 0) root->rchild = build(pre+1+leftL, mid+1+leftL, rightL);
    return root;
}
void ino(Node* root) {
    if(root == NULL) return;
    if(root->lchild) ino(root->lchild);
    printf("%d ", root->value);
    if(root->rchild) ino(root->rchild);
}
void fino(Node* root) {
    Node* p = root;
    stack<Node*> S;
    while(1) {
        if(p != NULL) {
            S.push(p);
            p = p->lchild;
        }
        else {
            if(S.empty()) return;
            p = S.top();
            S.pop();
            printf("%d ", p->value);
            p = p->rchild;
        }
    }
}
int main() {
    int preSeq[] = {1, 2, 4, 7, 3, 5, 6, 8};
    int inoSeq[] = {4, 7, 2, 1, 5, 3, 8, 6};
    Node* root = build(preSeq, inoSeq, 8);
    ino(root);
    printf("\n");
    fino(root);
    return 0;
}

posted @ 2013-02-02 10:02  小尼人00  阅读(174)  评论(0编辑  收藏  举报