1020 Tree Traversals

  • 构造树时,注意区间无效时,一定要回到上一位置
  • 通过计数保证层序最后一个结点不输出空格
struct Node
{
    int val;
    Node *left = nullptr, *right = nullptr;
    Node(int v)
        :val(v)
    {}
};
int N;
Node * build_tree(const vector<int> &post_order,
                  const vector<int> &in_order,
                  int &cur_idx,
                  int in_left,
                  int in_right)
{
    if(in_left > in_right)
    {
        cur_idx++; // 这里注意区间无效时,一定要回到上一位置
        return nullptr;
    }
    
    int cur_node_val = post_order[cur_idx];
    Node *cur = new Node(cur_node_val);
    
    if(in_left == in_right)
        return cur;

    int idx_r = 0;
    for(int i = 0; i < N; ++i)
        if(in_order[i] == cur_node_val)
            idx_r = i;
    
    cur->right = build_tree(post_order, 
                            in_order, 
                            --cur_idx,
                            idx_r + 1,
                            in_right);
    
    cur->left = build_tree(post_order, 
                           in_order, 
                           --cur_idx,
                           in_left,
                           idx_r - 1);

    return cur;
}

void level_order(Node *root)
{
    queue<Node*> q;
    q.push(root);
    
    int count = 0;
    while(!q.empty())
    {
        Node *cur = q.front();
        q.pop();
        count ++;
        
        cout << cur->val;

        // 层序最后一个结点不输出空格
        if(count != N)
            cout << " ";
            
        if(cur->left)
            q.push(cur->left);
        if(cur->right)
            q.push(cur->right);
    }
}

int main()
{
    cin >> N;
    vector<int> post_order(N);
    vector<int> in_order(N);
    
    for(int i = 0; i < N; ++i)
        cin >> post_order[i];
    
    for(int i = 0; i < N; ++i)
        cin >> in_order[i];
    
    int t = N - 1;
    Node *root = build_tree(post_order, in_order, t, 0, N - 1);
    level_order(root);
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值