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、递归的将左右子树也按照上述规律进行构造,最终还原二叉树。
代码:
/**
* Definition for a binary tree node.
* 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) {
return buildSubtree(preorder, inorder, ,
preorder.size()-,
, inorder.size()-);
} TreeNode* buildSubtree(vector<int>& preorder, vector<int>& inorder,
int p_left, int p_right, int i_left, int i_right) {
if (p_left > p_right || i_left > i_right)
return NULL; int root = preorder[p_left];
TreeNode* node = new TreeNode(preorder[p_left]); int range = ;
for (int j = i_left; j <= i_right; ++j) {
if (root == inorder[j]) {
range = j - i_left;
break;
}
} node->left = buildSubtree(preorder, inorder,
p_left + , p_left + range,
i_left, i_left + range - );
node->right = buildSubtree(preorder, inorder,
p_left + range + , p_right,
i_left + range + , i_right);
return node;
}
};