根据前序遍历和中序遍历构建二叉树

该文提供两种方法,分别使用C++和Java,通过中序和后序遍历序列来重构二叉树。代码实现了从给定的两个数组构建二叉树节点,首先创建根节点,然后利用栈或队列处理左右子节点的构建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

struct Node{
    int val;
    Node* left;
    Node* right;
    Node(int x):val(x),left(nullptr),right(nullptr) {}
};

Node* buidTree(std::vector<int> pre_order, std::vector<int> in_order) {
    Node* root = nullptr;
    if (pre_order.empty()) {
        return root;
    }
    std::stack<node*> st;
    root = new Node(pre_order[0]);
    st.push(root);
    int in_idx = 0;
    for (int pre_idx = 1; pre_idx < pre_order.size(); pre_idx++) {
        int val = pre_order[pre_idx];
        node* cur = st.top();
        if ( cur->val != in_order[in_idx]) {
            cur->left = new Node(val);
            st.push(cur->left);
        } else {
            while(!st.empty() && st.top()->val == in_order[in_idx]) {
                cur = st.top();
                st.pop();
                in_idx ++;
            }
            cur->right = new Node(in_order[in_idx]);
            st.push(cur->right);
        }
    }
    return root;
}

通过中序和后续,重构二叉树:

// 通过中序和后续,重构二叉树:
Node* buidTree(std::vector<int> post_order, std::vector<int> in_order) {
	if (post_order.empty()) {
	    return nullptr;
    }
    int size = post_order.size();
    Node* root = new Node(post_order[size - 1]);
    std::stack<Node*> st;
    st.push(root);
    int in_idx = size-1;
    for (auto idx=size-2; idx >= 0; idx--) {
        int val = post_order[idx];
        Node* cur = st.top();
        if (cur->val != in_order(in_idx)) {
            cur->right = new Node(val);
            st.push(cur->right);
        } else {
            if (!st.empty() && st.top()->val == in_order(in_idx)) {
                cur = st.top()
                st.pop();
                in_idx --;
            }
            cur->right = new Node(val);
            st.push(cur->right);
        }
   }
   return root;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值