zoukankan      html  css  js  c++  java
  • 用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》

  • 相关阅读:
    poj1258
    poj1012 模拟
    poj模拟1013
    《转》用人单位与职场新人的四大分歧
    weblogic启动时错误
    Oracle HRMS,PeopleSoft HR,SAP HR区别 主流HR软件对比分析
    Android数据库 之 SQLite数据库
    学习Oracle数据库(2)SQLPLUS介绍
    学习Oracle数据库(1)写在前面的话
    学习Oracle数据库(4)在表上建立不同类型的约束
  • 原文地址:https://www.cnblogs.com/DianeSoHungry/p/8891148.html
Copyright © 2011-2022 走看看