構建二叉樹(前/後序+中序)

構造二叉樹可以通過 前序+中序 、後序+中序兩種方法。

這兩種方法的核心思路都是 通過前/後序確定二叉樹的根節點,然後在中序中根據根節點進行劃分。然後遞歸。

 

前序+中序

class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        return BuildTree(0,pre.size()-1,0,vin.size()-1,pre,vin);
    }
    TreeNode* BuildTree(int leftpre,int rightpre,int leftin,int rightin,vector<int> pre,vector<int> vin){
        if(leftin>rightin)return NULL;
        TreeNode* root=new TreeNode(pre[leftpre]);
        int rootin=leftin;
        while(rootin<=rightin&&pre[leftpre]!=vin[rootin])rootin++;
        int left=rootin-leftin;
        root->left=BuildTree(leftpre+1,leftpre+1+left-1,leftin,rootin-1,pre,vin);
        root->right=BuildTree(leftpre+left+1,rightpre,rootin+1,rightin,pre,vin);
        return root;
    }
};

 

後序+中序(引用leetcode“寶寶可乖了”)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章