美文网首页
C++ 根据先序和中序构造二叉树

C++ 根据先序和中序构造二叉树

作者: 帅番茄 | 来源:发表于2017-04-20 22:28 被阅读0次
    struct Node{
        char val;
        Node* left;
        Node* right;
        Node(char a): val(a), left(NULL), right(NULL){}
    };
    
    void buildBinaryTreeAccordingPreAndInOrder(string preOrder, string inOrder, int length, Node* &head){
        if(length<1) return ;
        char data = preOrder[0];
        Node* tempPoint = new Node(data);
        head  = tempPoint;
        int indexOfInOrder = (int)inOrder.find(data);
        string leftInOrder = inOrder.substr(0, indexOfInOrder);
        string rightInOrder = inOrder.substr(indexOfInOrder+1);
        string leftPreOrder = preOrder.substr(1, indexOfInOrder);
        string rightPreOrder = preOrder.substr(indexOfInOrder+1);
        buildBinaryTreeAccordingPreAndInOrder(leftPreOrder, leftInOrder, indexOfInOrder, head->left);
        buildBinaryTreeAccordingPreAndInOrder(rightPreOrder, rightInOrder, length-indexOfInOrder-1, head->right);
    }
    

    相关文章

      网友评论

          本文标题:C++ 根据先序和中序构造二叉树

          本文链接:https://www.haomeiwen.com/subject/qlrrzttx.html