链接: 从前序与中序遍历序列构造二叉树
题目描述
算法分析
编程代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* _bulid(vector<int>& preorder,vector<int>& inorder,int inbegin,int& orderi,int inend)
{
if(inbegin > inend)
{
return nullptr;
}
TreeNode* root = new TreeNode(preorder[orderi]);
//找到中序遍历的根节点
int rooti = inbegin;
while(rooti <= inend)
{
if(preorder[orderi] == inorder[rooti])
{
orderi++;
break;
}
rooti++;
}
root->left = _bulid(preorder,inorder,inbegin,orderi,rooti-1);
root->right = _bulid(preorder,inorder,rooti+1,orderi,inend);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int i = 0;
TreeNode* root =_bulid(preorder,inorder,0,i,inorder.size()-1);
return root;
}
};