2021/3/1刷题小结

Rebuild binary tree

在这里插入图片描述

Scene reproduction

When tried to solve this question, I first simulate the process of rebuild binary tree by hand, and I found that the root could be determined from the preorder traversal, and then separate the inorder traversal into two part recursively, then found the children in the two parts. However, I didn’t do well in simplifying the recursive process, which led to my confusing into the condition to return. What’s more, I didn’t discover that the preorder sequence should also be separated in each recursive time, which made my result wrong.
After referring to the sample code posted by a net friend, I clear the way to solve the question better.

Solution

The process is recurssive, but we should take the easiest case at the beginning, then replace the case to the function.
The easiest case is that, after all the children is determined, we need to add them to the root. The root is the first element of the preorder sequence.
At first, we make a TreeNode whose value is pre[0], then we find the value in the vin[i2,j2] vector, after finding its position, we separate the vin vector into two part: left and right, and then, solve left and right sub question. We should notice that, when the vin vector is separated to left:vin[i2,i-1] and right: vin[i+1,j2] ,the pre[i1,j1] should be separated into left: pre[i1, i1+i-i2] and right right: pre[i1+i-i2,j2], so that the program can choose the correct root of left and right from their pre sequence.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> pre1, vin1;
    TreeNode* find(int i1, int j1, int i2, int j2){
        // find the root
        if(i1>j1||i2>j2){
            return NULL;
        }

        int rootval = pre1[i1];
        TreeNode* root = new TreeNode(rootval);
        // error: write < instead of <=
        for(int i = i2; i<=j2; i++){
            if(vin1[i] == rootval){
                // ? Why do we need to -i2 ?
                root->left = find(i1+1,i1+i-i2,i2,i-1);
                root->right = find(i1+i-i2+1,j1,i+1,j2);
            }
        }
        return root;
    }
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        // initial
        int n = vin.size();
        pre1 = pre;
        vin1 = vin;
        TreeNode* res = find(0,n-1,0,n-1);
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值