1.单值二叉树
PS——OJ题里面尽量不要适用全局变量
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 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 isSameTree(root->left,subRoot) || isSameTree(root->right,subRoot);
}
4.二叉树遍历
#include <stdio.h>
#include <stdlib.h>
struct TreeNode
{
char val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* rebulidTree(char* str,int* pi)
{
if(str[*pi] == '#')
{
(*pi)++;
return NULL;
}
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root ->val = str[(*pi)++];
root->left = rebulidTree(str, pi);
root->right = rebulidTree(str, pi);
return root;
}
void InOrder(struct TreeNode* root)
{
if(root == NULL)
return ;
InOrder(root->left);
printf("%c ",root->val);
InOrder(root->right);
}
int main()
{
char str[100];
scanf("%s ",str);
int i = 0;
struct TreeNode* root = rebulidTree(str, &i);
InOrder(root);
return 0;
}