144. 二叉树的前序遍历 - 力扣(LeetCode)
int TreeSize(struct TreeNode* root)
{
if (root == NULL)
return 0;
else
return 1 + TreeSize(root->left) + TreeSize(root->right);
}
void _preorderTraversal(struct TreeNode* root,int*array,int* pi)
{
if(root==NULL)
return;
array[(*pi)++]=root->val;
_preorderTraversal(root->left,array,pi);
_preorderTraversal(root->right,array,pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int size=TreeSize(root);
int *array=(int*)malloc(sizeof(int)*size);
int i=0;
_preorderTraversal(root,array,&i);
*returnSize=size;
return array;
}
965. 单值二叉树 - 力扣(LeetCode)
我写的。
int TreeSize(struct TreeNode*root)
{
if(root==NULL)
return 0;
else
return 1+TreeSize(root->left)+TreeSize(root->right);
}
void PrevOrder(struct TreeNode* root,int* a,int val)
{
if (root == NULL)
return;
if(root->val==val)
(*a)++;
PrevOrder(root->left,a,val);
PrevOrder(root->right,a,val);
}
bool isUnivalTree(struct TreeNode* root) {
if(root==NULL)
return true;
int val=root->val;
int a=0;
int size=TreeSize(root);
PrevOrder(root,&a,val);
if(a==size)
return true;
else
return false;
}
bool isUnivalTree(struct TreeNode* root) {
if(root==NULL)
return true;
//当前树
if(root->left&&root->val!=root->left->val)
return false;
if(root->right&&root->val!=root->right->val)
return false;
//递归判断左右子树
return isUnivalTree(root->left)&&isUnivalTree(root->right);
}
104. 二叉树的最大深度 - 力扣(LeetCode)
int maxDepth(struct TreeNode* root) {
if(root==NULL)
return 0;
int leftDepth=maxDepth(root->left);
int rightDepth=maxDepth(root->right);
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
226. 翻转二叉树 - 力扣(LeetCode)
struct TreeNode* invertTree(struct TreeNode* root) {
if(root==NULL)
return NULL;
else
{
struct TreeNode*tmp=root->left;
root->left=root->right;
root->right=tmp;
invertTree(root->left);
invertTree(root->right);
return root;
}
}
100. 相同的树 - 力扣(LeetCode)
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
if(p==NULL&&q==NULL)
return true;
if(p==NULL&&q!=NULL)
return false;
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);
}
572. 另一棵树的子树 - 力扣(LeetCode)
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
if(p==NULL&&q==NULL)
return true;
if(p==NULL&&q!=NULL)
return false;
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* s, struct TreeNode* t){
if(s==NULL)
return false;
if(isSameTree(s,t))
return true;
return isSubtree(s->left,t)||isSubtree(s->right,t);
}