今天继续学习了二叉树的性质,今天学习的性质没有昨天的多,还有就是,作业题的解题思路我也写在博客里吧!
一、查找二叉树中的结点
这里要注意:每次返回之后,如果没有接收,那么返回的值会被丢弃。
BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
if(root == NULL)
{
return NULL;
}
if(root->data == x)
{
return root;
}
BTNode* ret1 = BinaryTreeFind(root->left,x);
if(ret1)
return ret1;
BTNode* ret2 = BinaryTreeFind(root->right,x);
if(ret2)
return ret2;
return NULL;
}
下面是我画的图解:递归的过程
二、判断两棵树是不是相同,结构和结点值都一样
bool isSameTree(BTNode* root1, BTNode* root2)
{
if(root1 ==NULL && root2==NULL)
{
reutrn true;
}
//特别注意,这里的两个if是不能换顺序的
if(root1==NULL || root2==NULL)//这个判断是考虑到上图中第二幅图的情况
return false;
if(root1->data != root2->data)
{
return false;
}
return isSameTree(root1->left,root2->left)&&isSameTree(root1->right,root2->right);
}
三、判断一棵树是不是单树
单树的意思是:每一个结点的值都是相等的
bool SimpleTree(BTNode* root)
{
if(root==NULL)
return ture;
if(root->left && root->left->data != root->data)
return false;
if(root->right && root->right->data != root->data)
return false;
return SimpleTree(root->left) && SimpleTree(root->right);
}
四、将一个数组里的元素按照先序遍历放入二叉树,然后再用中序遍历打印出来
BTNode* rebulidTree(char* str, int* i)
{
if (str[*i] == '#')
{
(*i)++;
return NULL;
}
BTNode* root = (BTNode*)malloc(sizeof(BTNode));
if (root == NULL)
{
return;
}
root->data = str[(*i)++];
root->left = rebulidTree(str, i);
root->right = rebulidTree(str, i);
return root;
}
BTNode* inOrder(BTNode* root)
{
if (root == NULL)
{
return;
}
inOrder(root->left);
printf("%c", root->data);
inOrder(root->right);
}