重建二叉树

        https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=196&tqId=37109&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Ftab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196%26page%3D1%26search%3D%25E9%2587%258D%25E5%25BB%25BA%25E4%25BA%258C%25E5%258F%2589%25E6%25A0%2591&difficulty=undefined&judgeStatus=undefined&tags=&title=%E9%87%8D%E5%BB%BA%E4%BA%8C%E5%8F%89%E6%A0%91        先上代码

class Solution {
public:
    TreeNode* _reConstructBinaryTree(vector &pre, int pre_start, int pre_end, vector &vin, int vin_start, int vin_end)
    {
        if(pre_start > pre_end || vin_start > vin_end)
        {
            return nullptr;
        }
        TreeNode* root = new TreeNode(pre[pre_start]);
        for(auto i = vin_start ; i<= vin_end;++i)
        {
            if(pre[pre_start] == vin[i])
            {
                root->left = _reConstructBinaryTree(pre, pre_start + 1 ,pre_start + 1 + i - vin_start -1 , vin,vin_start ,i -1);
                root->right = _reConstructBinaryTree(pre, pre_start+ i - vin_start  +1,pre_end , vin, i + 1,vin_end);
                break;
            }
        }
        return root;
    }
    TreeNode* reConstructBinaryTree(vector pre,vector vin) {
            if(pre.empty()|| vin.empty() || pre.size() != vin.size()) return nullptr;
            return  _reConstructBinaryTree(pre,0,pre.size() -1,vin,0,vin.size() - 1);
    }
};

列子1:

输入:

[1,2,4,7,3,5,6,8],[4,7,2,1,5,3,8,6]

复制

返回值:

{1,2,3,4,#,5,6,#,7,#,#,8}

复制

说明:

返回根节点,系统会输出整颗二叉树对比结果,重建结果如题面图示    

重建二叉树_第1张图片

         

本题重点是要注意左右子树开始结束位置,结束位置是 i 位置相对起始位置的长度,没次找到根节点在递归创建左右子树

你可能感兴趣的:(蓝桥杯,职场和发展)