(樹)根據中序後序構建二叉樹

Kobe10發表於2017-02-03
  • 題目:根據中序和後序遍歷構建二叉樹
  • 思路:利用遞迴加上分治的思想。先找到根節點的值,然後在根據中序遍歷找到根節點的左右兩邊的值,然後在遞迴的處理左右兩邊的左右子樹。這裡的關鍵在於怎麼處理遞迴的左右子樹的範圍,程式碼裡面詳細解釋
  • 程式碼:
    class Solution {
    public:
        TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
            vector<int>::size_type lenIn = inorder.size();
            vector<int>::size_type lenPost = postorder.size();
            return buildTree_Aux(inorder,0,lenIn-1,postorder,0,lenPost-1);
        }
         
        TreeNode *buildTree_Aux(vector<int> &inorder,int inB,int inE,
                                vector<int> &postorder,int poB,int poE) {
            if(inB > inE || poB > poE)
                return NULL;
            //在後序遍歷中確定根節點
            TreeNode* root = new TreeNode(postorder[poE]);
            //在中序遍歷中確定左右子樹
            vector<int>::iterator iter = find(inorder.begin()+inB,inorder.begin()+inE,postorder[poE]);
            int index = iter - inorder.begin();//根節點的位置
    root
    ->left = buildTree_Aux(inorder,inB,index-1,postorder,poB,poB+index-1-inB);
       //這裡postorder,poB,poB+index-1-inB這部分表示後序的左子樹。pob是開始位置,index-1-inB是後序左子樹的節點數的個數。poB+index-1-inB是後序的左子樹的尾部 root
    ->right = buildTree_Aux(inorder,index+1,inE,postorder,poB+index-inB,poE-1);
       //這裡postorder,poB+index-inB,poE-1這部分表示後序的右子樹。poB+index-inB右子樹開始位置,poE-1右子樹結束位置,去掉了根節點的值(最尾部)
    return root; } };

     

  • 題目:根據前序和中序遍歷構建二叉樹
  • 思路:類似
  • 程式碼:
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            vector<int>::size_type lenIn = inorder.size();
            vector<int>::size_type lenPre = preorder.size();
            return buildTree_Aux(preorder, 0, lenPre-1, inorder, 0, lenIn-1);
        }
         TreeNode *buildTree_Aux(vector<int> &preorder,int prb,int pre,
                                 vector<int> &inorder,int inb,int ine) {
             if (prb > pre || inb > ine)
                 return NULL;
             TreeNode *root = new TreeNode(preorder[prb]);
             vector<int>::iterator iter = find(inorder.begin()+inb,inorder.begin()+ine,preorder[pre]);
             int mid = iter - inorder.begin();
             root->left = buildTree_Aux(preorder, prb+1, prb+mid-inb, inorder, inb, mid-1);
             root->right = buildTree_Aux(preorder, prb+1+mid-inb, pre, inorder, mid+1, ine);
             return root;
         }
    };

     

相關文章