目录
a. 二叉树的概念以及实现参照博客:
二叉树的概念 二叉树链式结构的实现,二叉树的基本操作
一、三道题的oj链接
1. 单值二叉树: oj链接
2. 相同的树:oj链接
3. 二叉树的前序遍历: oj链接
二、每题讲解
1.单值二叉树
a. 题目:
b. 题目所给代码
bool isUnivalTree(struct TreeNode* root) {
}
c. 思路
d. 代码:
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. 相同的树
a. 题目
b. 题目所给代码
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
}
c. 思路
d. 代码
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. 二叉树的前序遍历
a. 题目
b. 题目所给代码
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
}
所给参数 int* returnSize:在这里返回数组后,不知数组的大小,凡是返回结果是一串值,存在一个数组,都会配一个 int* returnSize来返回这个数组的大小
c. 思路
d. 代码
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) {
int n = TreeSize(root);
int*a = (int*)malloc(sizeof(int)*n);
*returnSize = n;
int i = 0;
preorder(root,a,&i);
return a;
}
a[ (*pi)++ ] = root->val;能够使每次的值都不会被销毁。
二叉树的oj题还会持续更新,关注主播,让我们一起学习,一起进步。