1.用非递归遍历求二叉树结点个数【计学2020】
算法思想:用先序非递归遍历
当前指针不为空或栈不为空进行循环;
当前指针不为空访问当前结点,当前节点入栈,进入左子树
当前指针为空,栈顶元素出栈(回溯),进入右子树
#include<malloc.h>
#define MaxSize 100
typedef struct node
{
int data;
struct node* left;
struct node* right;
}BTNode;
BTNode* BuyNode(int a)//a是要创建的值
{
BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));//定义临时变量扩容
if (newnode == NULL)
{
printf("malloc fail");//扩容失败
return NULL;
}
newnode->data = a;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
BTNode* BinaryTreeCreate()//二叉树一般需要手动扩建
{
BTNode* n1 = BuyNode(5);
BTNode* n2 = BuyNode(4);
BTNode* n3 = BuyNode(6);
BTNode* n4 = BuyNode(2);
BTNode* n5 = BuyNode(1);
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
return n1;
}
int preOrder(BTNode* T)
{
BTNode* stack[MaxSize];
int count = 0;//节点个数
int top = -1;//栈顶指针
BTNode* cur = T;
while(cur != NULL || top != -1)
{
if(cur != NULL)
{
count++;//相当于根 ,计数器
stack[++top] = cur;//入栈
cur = cur->left;//遍历左子树
}
else
{
cur = stack[top];
top--;//栈顶元素出栈
cur = cur->right;//遍历右子树
}
}
return count;
}
// 二叉树前序遍历
void BinaryTreePrevOrder(BTNode* root)
{
if (root == NULL)
{
return;
}
printf("%d ", root->data);//打印节点
BinaryTreePrevOrder(root->left);//访问左节点
BinaryTreePrevOrder(root->right);//访问右节点
}
int main()
{
BTNode* T = BinaryTreeCreate();//创建二叉树
printf("%d",preOrder(T));
BinaryTreePrevOrder(T);
return 0;
}
2.判断二叉树中是否有平衡结点
算法思想:
递归三部曲
1、找递归终止条件
2、找返回值:应该给上一级返回什么信息?
3、本级递归应该做什么:在这一级递归中,应该完成什任务?本级递归需要算出左子树之和与右子树之和并比较
int postOrder(BTNode* root,bool* have)
{
if(root == NULL)//
return 0;
if(root->left == NULL && root->right == NULL)//递归终止条件
{
return root->data;
}
int leftSum = postOrder(root->left, have);
int rightSum = postOrder(root->right, have);
if(leftSum == rightSum)
{
*have = true;
}
return leftSum + rightSum + root->data;//返回给上一层的信息:算出左右子树以及当前节点之和
}
int isBalance(BTNode* root)
{
bool have = false;
postOrder(root,&have);
return have;
}