給定後序遍歷和中序遍歷順序構造二叉樹

  1. postorder的最後一位是root;
  2. 從頭開始遍歷inorder輸出, 直到找到root, 計數個數爲左子樹個數j;
  3. 確定第一層左子樹右子樹的索引位置:
    • postorder: 左子樹0 - j-1, 右子樹 j+1 - length-2
    • inorder: 左子樹0- j-1, 右子樹 j + 1 - length -1
  4. 分別遞歸下一層
/**
    4
   / \
  3   7
    /  \ 
   5    6
 */
// inorder:  3 4 5 7 6
// postorder: 3, 5, 6, 7, 4

#include <iostream>
#include <vector>

struct Node {
    int value;
    struct Node* left;
    struct Node* right;

    Node(int val):
        value(val) {}
};

struct Node* buildBinaryTree(const std::vector<int>& postorder, int post_start, int post_end, const std::vector<int>& inorder, int in_start, int in_end) {
    struct Node* root = new Node(postorder[post_end]);

    if (post_end - post_start == 0) {
        return root;
    }

    int j = -1;
    while (inorder[in_start + ++j] !=  root->value && in_start + j <= in_end) ;

    if (j > in_end) {
        throw std::range_error("can't find root:" + std::to_string(root->value));
    }

    root->left = buildBinaryTree(postorder, post_start, post_start + j - 1, inorder, in_start, in_start + j - 1);
    root->right = buildBinaryTree(postorder, post_start + j, post_end - 1, inorder, in_start + j + 1, in_end);
    return root;
}

void inorder_print(struct Node* root) {
    if (root == nullptr) return;
    inorder_print(root->left);
    std::cout << root->value << std::endl;
    inorder_print(root->right);
}

int main() {
    std::vector<int> post_order = {3, 5, 6, 7, 4};
    std::vector<int> in_order = {3, 4, 5, 7, 6};

    struct Node* root = buildBinaryTree(post_order, 0, post_order.size() - 1, 
        in_order, 0, in_order.size() - 1);

    inorder_print(root);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章