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 3 / / 4 5 6 7
先序遍历结果为:1 2 4 5 3 6 7
中序遍历结果为:4 2 5 1 6 3 7
由此可以发现规律:
1、先序遍历的第一个字符,就是根结点(1)
2、发现根节点后,对应在中序遍历中的位置,则在中序遍历队列中,根节点左边的元素构成根的左子树,根的右边元素构成根的右子树;
3、递归的将左右子树也按照上述规律进行构造,最终还原二叉树。
代码:
1 /** 2 * Definition for a binary tree node. 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 return buildSubtree(preorder, inorder, 0, 14 preorder.size()-1, 15 0, inorder.size()-1); 16 } 17 18 TreeNode* buildSubtree(vector<int>& preorder, vector<int>& inorder, 19 int p_left, int p_right, int i_left, int i_right) { 20 if (p_left > p_right || i_left > i_right) 21 return NULL; 22 23 int root = preorder[p_left]; 24 TreeNode* node = new TreeNode(preorder[p_left]); 25 26 int range = 0; 27 for (int j = i_left; j <= i_right; ++j) { 28 if (root == inorder[j]) { 29 range = j - i_left; 30 break; 31 } 32 } 33 34 node->left = buildSubtree(preorder, inorder, 35 p_left + 1, p_left + range, 36 i_left, i_left + range - 1); 37 node->right = buildSubtree(preorder, inorder, 38 p_left + range + 1, p_right, 39 i_left + range + 1, i_right); 40 return node; 41 } 42 };