[LeetCode]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.
/** * 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 *DFS(vector<int> &preorder, vector<int> &inorder,int leftstart,int leftend,int rightstart,int rightend) { if(leftend-leftstart<0||rightend-rightstart<0) return NULL; TreeNode *root=new TreeNode(preorder[leftstart]); int pos;//中序遍历中根结点位置 for(int i=rightstart;i<=rightend;i++) { if(inorder[i]==preorder[leftstart]) { pos=i; break; } } int len=pos-rightstart; root->left=DFS(preorder,inorder,leftstart+1,leftstart+len,rightstart,pos-1); root->right=DFS(preorder,inorder,leftstart+len+1,leftend,pos+1,rightend); return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { return DFS(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1); } };