zoukankan      html  css  js  c++  java
  • 由二叉树先序遍历序列和后序遍历序列建二叉树

    思路:

    1.采用递归的思想建树

    2.先序遍历序列的第一个元素始终是当前子树的根;

    3.在中序遍历序列中以根节点为中心,前面的是左子树的先序遍历序列,后面的右子树的先序遍历序列;

    #include<iostream>
    #include<string>
    using namespace std;
    struct Node
    {
            char data;
            Node* lchild;
            Node* rchild;
    };
    void PreOrder(Node* root)
    {
            if(root!=NULL)
            {
                    cout<<root->data;
                    PreOrder(root->lchild);
                    PreOrder(root->rchild);
            }
    }
    void BuildTree(string sPre,string sMid,Node* &root)
    {
            if(sPre.length()==0||sMid.length()==0) return;
            root=new Node;
            root->data=sPre[0];
            int index=sMid.find(sPre[0]);
            BuildTree(sPre.substr(1,index+1),sMid.substr(0,index),root->lchild);
            BuildTree(sPre.substr(index+1),sMid.substr(index+1),root->rchild);
    
    }
    int main()
    {
            string s1="abdecfg";
            string s2="dbeafcg";
            Node* root=NULL;
            BuildTree(s1,s2,root);
            PreOrder(root);
            cout<<endl;
            return 0;
    }
    

      

  • 相关阅读:
    函数名的使用-闭包-迭代器
    函数
    文件操作
    基础数据补充
    python基础-数据类型(2)
    python基础-数据类型(1)
    PHP 缓存技术(一)
    linux学习笔记整理(九)
    linux学习笔记整理(八)
    linux学习笔记整理(七)
  • 原文地址:https://www.cnblogs.com/liujiangyi/p/2747229.html
Copyright © 2011-2022 走看看