题解 | #重建二叉树#

重建二叉树

http://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        if(pre.size()==0 || vin.size()==0)    return nullptr;

        // 找到根节点的值,并构建根节点
        int rootval = pre[0];
        TreeNode* root = new TreeNode(rootval);

        // 找到根节点在中序数组中的位置,可以标志左右子树的节点各有多少个
        int index=0;
        for(; index<vin.size(); index++) {
            if(vin[index] == rootval) {
                break;
            }
        }
        // 切割数组 vin
        vector<int> vinleft(vin.begin(), vin.begin()+index);
        vector<int> vinright(vin.begin()+index+1, vin.end());
        // 切割数组 pre
        vector<int> preleft(pre.begin()+1, pre.begin()+1+index);
        vector<int> preright(pre.begin()+1+index, pre.end());

        // 递归生成左右子树
        root->left = reConstructBinaryTree(preleft, vinleft);
        root->right = reConstructBinaryTree(preright, vinright);

        // 返回根节点
        return root;
    }
};
全部评论

相关推荐

生命诚可贵:先不说内容怎么样 排版就已经太差劲了 第一眼看不到重点,第二眼已经没有再看的耐心了, 篇幅占的太满了 字体不要用灰色 观感不好 想重点突出的黑色加粗就可以了 多列要点 少些大段的句子 项目经历把项目用的技术要点列出来,光写个python plc什么的太宽泛了 自我评价也有点偏多
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客企业服务