1.从中序与后序遍历序列构造二叉树
class Solution{
public:
TreeNode* buildTree(vector<int>& inorder,vector<int>& postorder){
if(inorder.size()==0||postorder.size()==0) return Null;
return build(inorder,0,inorder.size()-1,postorder,0,postorder()-1);
build(vector<int>& inorder, int is, int ie,vector<int>& postorder , int ps ,int pe){
TreeNode* root = new TreeNode(postorder[pe]);
int i = is;
while(i<ie&&postorder[pe]!=inorder[i])
{
i++;
}
int leftLen = i-is;
int rightLen = ie - i;
if(leftLen>0){
roo->left = build(inorder,is,is+leftLen-1,postorder,ps,ps+leftLen-1);
}
if(rightLen>0)
{
root->right = build(inorder,is+leftLen+1,ie,postorder,ps+leftLen,pe-1);
}
return root;
}
2.从前序与中序遍历序列构造二叉树
class Solution{
public:
TreeNode* buildTree(vector<int>&preorder,vector<int>& inorder){
if(preorder.size()==0||inorder.size()==0) return NULL;
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* build(vector<int>&preorder,int ps.int pe,vector<int>&inorder,int is,int ie){
TreeNode* root = new TreeNode(preorder[ps]);
int i =is;
while(i<ie&&preorder[ps]!=inorder[i])
{
i++;
}
int leftLen = i-is;
int rightLen = ie - i;
if(leftLen>0)
{
root->left = build(preorder,ps+1,ps+leftLen,inorder,is,is+leftLen-1);
}
if(rightLen>0)
{
root->right = build(preorder,ps+1+leftLen,pe,inorder,is+1+leftLen,ie);
}
return root;
}
};
3.填充每个节点的下一个右侧节点指针(完美二叉树)
class Solution{
public:
void createconnect(Node* Left,Node* Right){
if(Left==nullptr||Left->next==Right) return;
Left->next=Right;
createconnect(Left->left,Left->right);
createconnect(Left->right,Right->left);
createconnect(Right->left,Right->right);
}
Node* connect(Node* root){
if(root!=nullptr) createconnect(root->left,root->right);
return root;
}
}
4.填充每个节点的下一个右侧节点指针(非完美二叉树)
class Solution{
public:
Node* connect(Node* root){
if(root==nullptr) return NULL;
if(root->left!=nullptr){
root->left->next = (root->right!=nullptr)? root->right;getNext(root->Next);
}
if(root->right!=nullptr){
root->right->next = getNext(root->Next);
}
connect(root->right);
connect(root->left);
return root;
}
Node* getNext(Node* uncle){
if(uncle==nullptr) return NULL;
if(uncle->left!=nullptr) return uncle->left;
if(uncle->right!=nullptr) return uncle->right;
return getNext(uncle->next);
}
};
5.二叉树最近公共祖先
class Solution{
public:
TreeNode* lowestCommonAncestor(TreeNode* root,TreeNode*p,TreeNode*q){
if(root==nullptr||root==q||root==p) return root;
TreeNode* left= lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if(left==nullptr) return right;
if(right==nullptr) return left;
return root;
}
}