Construct Binary Tree from Preorder and Inorder Traversal
Q:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
A:
/** * 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 *buildTree(vector<int> &preorder, vector<int> &inorder) { // Start typing your C/C++ solution below // DO NOT write int main() function if (inorder.empty() || preorder.empty()) return NULL; return buildTreeInternal(inorder, 0, inorder.size() - 1, preorder, 0); } private: TreeNode *buildTreeInternal(vector<int> &inorder, int start, int end, vector<int> &preorder, int root_pos_pre) { if (start > end) return NULL; int root_pos_in = -1; for (int i = start; i <= end; ++i) { if (inorder[i] == preorder[root_pos_pre]) { root_pos_in = i; break; } } if (-1 == root_pos_in) { assert(0); return NULL; } TreeNode* root = new TreeNode(preorder[root_pos_pre]); if (start <= root_pos_in - 1) { root->left = buildTreeInternal(inorder, start, root_pos_in - 1, preorder, root_pos_pre + 1); root_pos_pre += root_pos_in - start; } if (end >= root_pos_in + 1) { root->right = buildTreeInternal(inorder, root_pos_in + 1, end, preorder, root_pos_pre + 1); } return root; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号