【牛客網】重建二叉樹

轉載於牛客網
- 題目描述:
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

  • 思路:
    首先我們可以在先序遍歷中找到根節點,即1,然後在中序遍歷中找到1的位置,此後在中序遍歷中1的左邊即爲左子數,1的右邊即爲右子數的內容。此後用相同的思路進行迭代即可重建此二叉樹。

  • 代碼:

int len = in.size();
    if (len == 0)return NULL;
    vector<int>left_pre, right_pre, left_in, right_in;
    //創建根節點
    TreeNode* head = new TreeNode(pre[0]);
    int gen = 0;
    //在中序遍歷中找到根節點的位置
    for (int i = 0; i < len; i++){
        if (in[i] == pre[0]){
            gen = i;
            break;
        }
    }
    //對中序而言,根節點左邊的位於二叉樹左子樹,右邊的爲二叉樹右子樹
    for (int i = 0; i < gen; i++){
        left_in.push_back(in[i]);
        left_pre.push_back(pre[i + 1]);
    }
    for (int i = gen + 1; i < len; i++){
        right_in.push_back(in[i]);
        right_pre.push_back(pre[i]);
    }
    //遞歸求下一部分
    head->left = reConstructBinaryTree(left_pre, left_in);
    head->right = reConstructBinaryTree(right_pre, right_in);
    return head;
發佈了37 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章