前序遍历和中序遍历树构造二叉树

根据中序遍历和后序遍历树构造二叉树

样例

样例 1:

输入:[],[]
输出:{}
解释:
二叉树为空

样例 2:

输入:[1,2,3],[1,3,2]
输出:{2,1,3}
解释:
二叉树如下
  2
 / \
1   3

注意事项

你可以假设树中不存在相同数值的节点

 

 

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    TreeNode * buildTree(vector<int> &preorder, vector<int> &inorder)
    {
        // write your code here
        int n  = preorder.size();
        TreeNode* ret =NULL;
        int *pre = new int[n];  
        if (!preorder.empty())  
        {  
            memcpy(pre, &preorder[0], n*sizeof(int));  
        }  
        int *in = new int[n];  
        if (!inorder.empty())  
        {  
            memcpy(in, &inorder[0], n*sizeof(int));  
        }
        
        
        
        ret = CreatBT1(pre, in, n);
        return ret;
    }
    
    
    TreeNode* CreatBT1(int* pre, int* in, int n)
    {
        TreeNode* b;
        int *p;
        int k ;
        if(n <= 0)
        {
            return NULL;
        }
        //b = (TreeNode*)malloc(sizeof(TreeNode));
        b = new TreeNode(*pre);
        //return b;
        //b->val = ;
        for(p=in; p<in+n; p++)
        {
            if(*p == *pre)
                break;
        }
        k = p-in;
        b->left = CreatBT1(pre+1, in, k);
        b->right = CreatBT1(pre+1+k, p+1, n-k-1);
        return b;
    }
};

 

上一篇:PAT Is It a Binary Search Tree(树)


下一篇:22 从前序与中序遍历序列构造二叉树(leecode 105)