[LeetCode] Construct Binary Tree from Inorder and Pretorder 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.
Solution:
/** * 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 *build(vector<int> &preorder, vector<int> &inorder, int pre_start, int pre_end, int in_start, int in_end) { if(pre_start > pre_end || in_start > in_end) return NULL; TreeNode *curRoot = new TreeNode(preorder[pre_start]); int rootIndex = -1; for(int i = in_start;i <= in_end;i++) { if(inorder[i] == preorder[pre_start]) { rootIndex = i; break; } } if(rootIndex == -1) return NULL; int leftNum = rootIndex - in_start; curRoot -> left = build(preorder, inorder, pre_start + 1, pre_start + leftNum, in_start, rootIndex - 1); curRoot -> right = build(preorder, inorder, pre_start + leftNum + 1, pre_end, rootIndex + 1, in_end); return curRoot; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { return build(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1); } };