tag:
- Medium夹界;
question
??Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
Example:
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
?/ \
15 7
思路:
??由于先序的順序的第一個(gè)肯定是根丙者,所以原二叉樹的根節(jié)點(diǎn)可以知道纷捞,題目中給了一個(gè)很關(guān)鍵的條件就是樹中沒有相同元素糜值,有了這個(gè)條件我們就可以在中序遍歷中也定位出根節(jié)點(diǎn)的位置耍攘,并以根節(jié)點(diǎn)的位置將中序遍歷拆分為左右兩個(gè)部分始鱼,分別對(duì)其遞歸調(diào)用原函數(shù)即可。代碼如下:
/**
* 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) {
if (preorder.size() != inorder.size()) return NULL;
return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
}
TreeNode* buildTree(vector<int>& preorder, int preLeft, int preRight, vector<int>& inorder, int inLeft, int inRight) {
if (preLeft > preRight || inLeft > inRight) return NULL;
int i = 0;
for (i=inLeft; i<inRight; ++i) {
if (preorder[preLeft] == inorder[i]) break;
}
TreeNode *cur = new TreeNode(preorder[preLeft]);
cur->left = buildTree(preorder, preLeft + 1, preLeft+i-inLeft, inorder, inLeft, i-1);
cur->right = buildTree(preorder, preLeft+i-inLeft+1, preRight, inorder, i+1, inRight);
return cur;
}
};