目录
1. 单值二叉树
题目
题目分析
代码实现
不带返回值版本
bool flag=true;
void PreOrderCompare(struct TreeNode* root ,int val)
{
if(root == NULL || flag ==false)//这里的判断条件flag==false就是(易错点1)说的
return;
if(root->val !=val)
{
flag=false;
return;//这里是找到了不同的值,就不要往下递归了,直接开始回退了
}
PreOrderCompare(root->left,val);
PreOrderCompare(root->right,val);
}
bool isUnivalTree(struct TreeNode* root){
if(root == NULL)
return true;
flag=true;//每次调用前序遍历,都要将flag初始化为true(易错点2)
PreOrderCompare(root,root->val);
return flag;
}
带返回值版本
bool isUnivalTree(struct TreeNode* root){
if(root == NULL)
return true;
if(root->left && root->left->val != root->val)
return false ;
if(root->right && root->right->val != root->val)
return false ;
return isUnivalTree(root->left)
&& isUnivalTree(root->right);
}
递归展开图
2. 相同的树
题目
题目分析
代码实现
bool isSameTree(struct TreeNode* p, struct TreeNode* q){
if(p==NULL && q==NULL)
return true;
if(p == NULL || q == NULL)
return false;
if(p->val != q->val)
return false;
return isSameTree(p->left,q->left)
&& isSameTree(p->right,q->right);
}
3. 对称二叉树
题目
题目分析
代码实现
bool isSymmetricsSubTree(struct TreeNode* root1,struct TreeNode* root2)
{
if(root1 == NULL && root2 ==NULL)
return true;
if(root1 == NULL || root2 == NULL)
return false;
if(root1->val != root2->val)
return false;
return isSymmetricsSubTree(root1->left,root2->right)
&& isSymmetricsSubTree(root1->right,root2->left);
}
bool isSymmetric(struct TreeNode* root){
if(root == NULL)
return true;
return isSymmetricsSubTree(root->left, root->right);
}
4. 另外一颗子树
题目
题目分析
代码实现
bool isSameTree(struct TreeNode* p, struct TreeNode* q){
if(p==NULL && q==NULL)
return true;
if(p == NULL || q == NULL)
return false;
if(p->val != q->val)
return false;
return isSameTree(p->left,q->left)
&& isSameTree(p->right,q->right);
}
bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot){
if(root == NULL)
return false;
if(isSameTree(root,subRoot))
return true;
return isSubtree(root->left,subRoot)
|| isSubtree(root->right,subRoot);
}
递归展开图
5. 二叉树的前、中、后序遍历
5.1 二叉树的前序遍历
题目
题目分析
代码实现
int Treesize (struct TreeNode* root)
{
return root == NULL ? 0 : Treesize(root->left) + Treesize(root->right) + 1;
}
void preorder (struct TreeNode* root, int* a , int* pi)
{
if(root == NULL)
return ;
a[(*pi)++] = root->val;
preorder(root->left, a, pi);
preorder(root->right, a, pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize = Treesize(root);
int* a=(int*)malloc(*returnSize * sizeof(int));
int i=0;
preorder(root, a, &i);
return a;
}