OJ题——二叉树(最大深度/平衡二叉树/前序遍历构建)

🍬个人主页:Yanni.—

🌈数据结构:Data Structure.​​​​​​

🎂C语言笔记:C Language Notes

🏀OJ题分享: Topic Sharing

题目一(最大深度)

利用分治的思想,将大问题转为小问题,可以看出最大深度=左子树与右子树之间最大的+1,依次类推。

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;
}

题目二(平衡二叉树)

首先判断左右两个大子树是否平衡,之后在把左右大子树分为小子树依次判断。

判断是否平衡,需要算出左右子树的最大深度,题目一给出了代码实现

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;
}

接着通过递归算法去判断是否平衡 

bool isBalanced(struct TreeNode* root) {
    if(root == NULL)
    {
        return true;
    }
    int leftDepth = maxDepth(root->left);
    int rightDepth = maxDepth(root->right);

    return abs(leftDepth - rightDepth) < 2 && isBalanced(root->left) && isBalanced(root->right);
}

题目三(前序遍历构建二叉树)

这道题是清华大学计算机的复试上机题。

构建二叉树结点

typedef struct TreeNode
{
	struct TreeNode* left;
	struct TreeNode* right;
	char val;
}TNode;

利用前序遍历构建二叉树

TNode* CreatTree(char* a, int* pi)
{
	if (a[*pi] == '#')
	{
		(*pi)++;
		return NULL;
	}

	TNode* root = (TNode*)malloc(sizeof(TNode));
	if (root == NULL)
	{
		printf("malloc fail!!!\n");
		exit(-1);
	}
	root->val = a[*pi];
	(*pi)++;
	root->left = CreatTree(a, pi);
	root->right = CreatTree(a, pi);
	
	return root;
}

中序遍历打印数据

void Inorder(TNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	Inorder(root->left);
	printf("%c", root->val);
	Inorder(root->right);
}

主函数测试

int main()
{
	char str[100];
	scanf("%c", str);

	int i = 0;
	TNode* root = CreatTree(str, &i);

	Inorder(root);
	return 0;
}

好啦,这就是今天学习的分享啦!看到希望大家的三连呀!

如果有不当之处,欢迎大佬指正!

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值