目录
前言
作为笔记存放着,忘记了的话会拿出来看看。
翻转二叉树
翻转二叉树就是把原二叉树镜像对称,采用递归算法
struct TreeNode* invertTree(struct TreeNode* root){
if(root==NULL)
return NULL;
struct TreeNode* tem=NULL;
tem=root->left;
root->left=root->right;
root->right=tem;
invertTree(root->left);
invertTree(root->right);
return root;
}
相同二叉树
判断两颗树是否相同
bool isSameTree(struct TreeNode* p, struct TreeNode* q){
if(q==NULL && p==NULL)
return true;
else if(q==NULL || p==NULL)
return false;
else if(q->val != p->val)
return false;
else
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
对称二叉树
和上面镜像的二叉树很想,但是该题是判断两棵树是否镜像对称
bool compare(struct TreeNode* left,struct TreeNode* right){
if(left==NULL && right==NULL)
return true;
else if(left==NULL || right==NULL)
return false;
else if(left->val != right->val)
return false;
return compare(left->left,right->right) && compare(left->right,right->left);
}
bool isSymmetric(struct TreeNode* root){
if(root==NULL)
return true;
return compare(root->left,root->right);
}
二叉树的另一颗子树
判断subRoot是否是root的一部分
bool issame(struct TreeNode* q,struct TreeNode* p){
if(q==NULL && p==NULL)
return true;
else if(q==NULL || p==NULL)
return false;
else if(q->val != p->val)
return false;
else
return issame(p->left,q->left) && issame(p->right,q->right);
}
bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot){
if(root==NULL )
return false;
return issame(root,subRoot) || isSubtree(root->left,subRoot) || isSubtree(root->right,subRoot);
}
平衡二叉树
平衡二叉树的定义为:一个二叉树每个节点左右两个子树的高度差的绝对值不超过1
int calculate(struct TreeNode* root){
if(root==NULL)
return 0;
return 1+fmax(calculate(root->left),calculate(root->right));
}
bool isBalanced(struct TreeNode* root){
if(root==NULL)
return true;
if(((calculate(root->left)-calculate(root->right)>=-1) && (calculate(root->left)-calculate(root->right)<=1)) && isBalanced(root->left) && isBalanced(root->right))
return true;
return false;
}