首页 > 代码库 > Construct Binary Tree from Preorder and Inorder Traversal

Construct Binary Tree from Preorder and Inorder Traversal

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

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

思路:递归。主要是注意调用时起始和终止的index。

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {13         TreeNode* root=process(preorder, 0,preorder.size(),inorder,0,inorder.size());14         return root;15     }16    TreeNode*  process(vector<int> &preorder, int s1, int e1, vector<int> &inorder, int start, int end)17     {18         if(start>=end)19         {20             return NULL;21         }22         int root_val=preorder[s1];23         int inorder_index=start;24         while(inorder_index<end)25         {26             if(inorder[inorder_index]==root_val)27             break;28             else inorder_index++;29         }30         int count=inorder_index-start;//做子树节点数量31         TreeNode* left=process(preorder, s1+1,s1+count+1,inorder,start,inorder_index);32         TreeNode* right=process(preorder,s1+count+1, e1,inorder, inorder_index+1,end);33         TreeNode* root=new TreeNode(root_val);34         root->left=left;35         root->right=right;36         return root;37     }38 };