🔥个人主页:guoguoqiang. 🔥专栏:我与C++的爱恋
从中序与后序遍历序列构造二叉树
/**
* 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>& inorder, vector<int>& postorder,int& posi,int inbegin,int inend){//通过后序确定根,然后通过中序确定左子树右子树
if(inbegin>inend)
return nullptr;
TreeNode* root=new TreeNode(postorder[posi--]);//根是由后序确定的,所以遍历时也需要按后序来走。
int rooti=inbegin;
while(rooti<=inend){//确定根在中序中的位置
if(inorder[rooti]==root->val)
break;
else
rooti++;
}
//[inbegin,rooti-1] rooti [rooti+1,inend]
root->right=_buildTree(inorder,postorder,posi,rooti+1,inend);
root->left=_buildTree(inorder,postorder,posi,inbegin,rooti-1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int i=postorder.size()-1;
TreeNode* root= _buildTree(inorder,postorder,i,0,inorder.size()-1);
return root;
}
};
从前序与中序遍历序列构造二叉树
/**
* 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& prei,int inbegin,int inend){
if(inbegin>inend)
return nullptr;
TreeNode* root=new TreeNode(preorder[prei++]);//前序确定根,(根,左子树,右子树)
int rooti=inbegin;
while(rooti<=inend){//在中序中找根节点
if(inorder[rooti]==root->val)
break;
else
rooti++;
}
//[inbegin,rooti-1] rooti [rooti+1,inend]
root->left=_buildTree(preorder,inorder,prei,inbegin,rooti-1);//遍历左子树
root->right=_buildTree(preorder,inorder,prei,rooti+1,inend);//遍历右子树
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int i=0;
TreeNode* root=_buildTree(preorder,inorder,i,0,inorder.size()-1);
return root;
}
};