给定后序遍历和中序遍历顺序构造二叉树

  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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值