LeetCode-105. 从前序与中序遍历序列构造二叉树

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:

    3
   / \
  9  20
    /  \
   15   7

 

 

剑指offer原题,值得细细品味,特别经典的利用递归构造二叉树题目

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */


class Solution {
public:
    TreeNode* buildTree(vector& preorder, vector& inorder) {
        if(preorder.size()==0 || preorder.empty() || inorder.empty())
            return NULL;

        return SetUpTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }

    TreeNode* SetUpTree(vector& preorder, int preStart, int preEnd,
                        vector& inorder, int inStart, int inEnd){

        TreeNode *root = new TreeNode(preorder[preStart]);
        int pos = findInRoot(root->val, inorder, inStart, inEnd);

        int leftSize = pos - inStart;
        int rightSize = inEnd - pos;

        if(leftSize > 0)
            root->left = SetUpTree(preorder, preStart+1, preStart+leftSize, inorder, inStart, inStart+leftSize-1);
        if(rightSize > 0)
            root->right = SetUpTree(preorder,preEnd-rightSize+1, preEnd, inorder, inEnd-rightSize+1,inEnd);

        return root;
    }

private:
    int findInRoot(int rootval, vector &arr, int inStart, int inEnd){
        for(int i=inStart;i <= inEnd;i++){
            if(arr[i]==rootval)
                return i;
        }
        return -1;
    }

};

 

你可能感兴趣的:(算法,C++,LeetCode,LeetCode,构造二叉树,前序遍历,中序遍历)