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


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

  • 相关阅读:
    Ajax跨域解决实例
    关于tween.js测试介绍
    signal() 和 sigaction()
    信号概述
    监控文件事件
    栈和栈帧
    进程结构和内存布局
    关于文件I/o的原子操作
    查询Linux系统中glibc的版本
    IOPS和Throughput
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787105.html
Copyright © 2020-2023  润新知