您的位置:首页 > 其它

[leetcode][tree] Construct Binary Tree from Preorder and Inorder Traversal

2015-05-20 21:38 465 查看
题目:

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.
/**
* 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.empty() || inorder.empty() || preorder.size() != inorder.size()) return NULL;
return buildTreeCore(preorder, 0, inorder, 0, preorder.size());
}
private:
int search(vector<int>& vec, int start, int len, int val){//在vec中的从start开始的len个元素中查找val,若找到,返回val在preorder中的位置;若找不到,返回-1;
int end = start + len;
for (int i = start; i < end; ++i){
if (vec[i] == val) return i;
}
return -1;
}
TreeNode* buildTreeCore(vector<int>& preorder, int preStart, vector<int>& inorder, int inStart, int len){
if (0 == len || preStart + len > preorder.size() || inStart + len > preorder.size()) return NULL;
TreeNode *root = new TreeNode(preorder[preStart]);
int index = search(inorder, inStart, len, preorder[preStart]);
if (-1 == index) return NULL;
int leftLen = index - inStart;//左子树节点个数
int rightLen = len - leftLen - 1;//右子树节点个数
int leftPreStart = preStart + 1;//前序序列中左子树的开始位置
int leftInStart = inStart;//中序序列中左子树的开始位置
int rightPreStart = preStart + 1 + leftLen;//前序序列中右子树的开始位置
int rightInStart = inStart + leftLen + 1;//中序序列中右子树的开始位置
if(leftLen > 0) root->left = buildTreeCore(preorder, leftPreStart, inorder, leftInStart, leftLen);
if(rightLen > 0) root->right = buildTreeCore(preorder, rightPreStart, inorder, rightInStart, rightLen);
return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐