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

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);
}
    原文作者:帅番茄
    原文地址: https://www.jianshu.com/p/b9c24c7c806c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞