105. Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
c++代码1:
/**
* 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* createTree(vector<int>& preorder,vector<int>& inorder,int preL,int preR,int inL,int inR){
//preL:先序遍历左边界 preR:先序遍历右边界
//inL:中序遍历左边界 inR:中序遍历右边界
if(preL>preR)return NULL;
TreeNode* root=new TreeNode(preorder[preL]);//新建树结点 树结点的值为preorder[preL]
int inPos;
for(inPos=inL;inPos<=inR;++inPos){//找出中序遍历序列中当前根节点的位置
if(preorder[preL]==inorder[inPos])break;
}
int leftTreeNodeCount=inPos-inL;//当前根节点左子树上的结点个数
//左子树的先序区间为[preL+1,preL+leftTreeNodeCount],中序区间[inL,inPos-1]
//返回左子树根节点指针给root->left
root->left=createTree(preorder,inorder,preL+1,preL+leftTreeNodeCount,inL,inPos-1);
//右子树的先序区间为[preL+leftTreeNodeCount+1,preR],中序区间[inPos+1,inR]
//返回右子树根节点指针给root->right
root->right=createTree(preorder,inorder,preL+leftTreeNodeCount+1,preR,inPos+1,inR);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return createTree(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
}
};