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

#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;
}

转载于:https://www.cnblogs.com/robbychan/archive/2013/02/02/3787105.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值