力扣——题目
运用迭代的方法去求解
/**
* 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* buildTree(vector<int>& preorder, vector<int>& inorder)
{
int prvei=0;
int begin=0;
int end=inorder.size()-1;
return _buildTree(preorder,inorder,prvei,0,end);
}
private:
TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder,int& prvei,int begin,int end)
{
if(begin>end)
return nullptr;
TreeNode*root=new TreeNode(preorder[prvei]);
int rooti=begin;
while(rooti<=end)
{
if(inorder[rooti]==preorder[prvei])
{
break;
}
else
rooti++;
}
prvei++;
root->left= _buildTree(preorder,inorder,prvei,begin,rooti-1);
root->right= _buildTree(preorder,inorder,prvei,rooti+1,end);
return root;
}
};