[Leetcode]Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:监控组态软件 编辑:程序博客网 时间:2024/06/05 20:38

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.


/** * 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:    /*algorithm: divde and conqure      [2,1,3] [1,2,3]    */    TreeNode* buildTreeSub(vector<int>& pre,int ps,vector<int>& in,int is,int size)    {        if(size==0)return NULL;        TreeNode* root = new TreeNode(pre[ps]);        //find index for pre[ps] in inorder array        int i;        for(i=0;i < size && in[is+i] != pre[ps];i++);        root->left = buildTreeSub(pre,ps+1,in,is,i);        root->right = buildTreeSub(pre,ps+i+1,in,is+i+1,size-(i+1));        return root;    }    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {            if(preorder.size() != inorder.size())return NULL;            return buildTreeSub(preorder,0,inorder,0,inorder.size());    }};


0 0