• 用C/C++码经典算法--树


    All rights reserved by DianeSoHungry (Qingyun Hu).
    Original URL: https://www.cnblogs.com/DianeSoHungry/p/8891148.html

    Contents

    • Construct a binary tree from DLR and LDR traversals.

    Problem 1

    Construct a binary tree from DLR and LDR traversals.
    (根据先序遍历和中序遍历序列,建二叉树)
    Example:
    Input:

    8
    1 2 4 7 3 5 6 8
    4 7 2 1 5 3 8 6
    

    Output:
    Head pointer of the built binary tree

    Intuition

    For each DLR, you know the first element correspond to the root node. By finding the first element of DLR in LDR, you can split out the subarray of DLR and LDR for left subtree, so as to the subarray of DLR and LDR for right subtree. That is, time for recursion.

    Solution in CPP

    #include<iostream>
    #include<queue>
    struct BtNode{
        int val;
        BtNode* left;
        BtNode* right;
        BtNode(int val): val(val), left(nullptr), right(nullptr){
            
        };
    };
    BtNode* BuildBT(int pre[], int mid[], int len){
        if (len == 0) {
            return nullptr;
        }
        BtNode* root;
        for (int i = 0; i < len; ++i) {
            if ( mid[i] == pre[0]) {
                root = new BtNode(mid[i]);
                root->left = BuildBT(pre+1, mid, i);
                root->right = BuildBT(pre+i+1, mid+i+1, len-i-1);
                break;
            }
        }
        
        return root;
    }
    void TraverseLevelwise(BtNode* bt){
        std::queue<BtNode*> q;
        q.push(bt);
        while (!q.empty()) {
            if (q.front() != nullptr) {
                std::cout << (q.front()->val) << " ";
                q.push(q.front()->left);
                q.push(q.front()->right);
            }
            else {
    //            std::cout << "null ";
            }
            
            q.pop();
        }
        std::cout << std::endl;
    }
    
    int main(){
        int n;
        std::cin >> n;
        int preorder[n];
        int midorder[n];
        for (int i = 0; i < n; ++i) {
            std::cin >> preorder[i];
        }
        for (int i = 0; i < n; ++i) {
            std::cin >> midorder[i];
        }
        BtNode* res = BuildBT(preorder, midorder, n);
        TraverseLevelwise(res);
        return 0;
    }
    

    After getting the binary tree, for checking, the level order of the tree is printed as below.

    1 2 3 4 5 6 7 8 
    

    Reference

    《剑指offer》

  • 相关阅读:
    树的直径 poj 2631
    hdu 3954 Level up(线段树)
    [Java Web]Struts2解决中文乱码问题
    怎样为virtualbox添加新的分辨率
    本人的cocos2d-x之路
    php 中利用json_encode和json_decode传递包括特殊字符的数据
    【设计模式】—— 创建者模式Builder
    【设计模式】——工厂方法FactoryMethod
    【Apache开源软件基金会项目】
    【设计模式】——抽象工厂Abstract Factory
  • 原文地址:https://www.cnblogs.com/DianeSoHungry/p/8891148.html
Copyright © 2020-2023  润新知