[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.
没什么好说的,了解原理即可,使用递归。
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, int a, int b, int n) { 13 TreeNode *root = NULL; 14 if (n < 1) { 15 return root; 16 } 17 root = new TreeNode(preorder[a]); 18 bool flag = false; 19 int i; 20 for (i = 0; i < n; ++i) { 21 if (inorder[b+i] == preorder[a]) { 22 break; 23 } 24 } 25 root->left = buildTree(preorder, inorder, a+1, b, i); 26 root->right = buildTree(preorder, inorder, a+i+1, b+i+1, n-1-i); 27 return root; 28 } 29 30 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { 31 int n = preorder.size(); 32 return buildTree(preorder, inorder, 0, 0, n); 33 34 } 35 };