leetcode-tree1

1.Invert Binary Tree  二叉树的镜像

2.Minimum Depth of Binary Tree  

3.Maximum Depth of Binary Tree

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

struct TreeNode* invertTree(struct TreeNode* root) {
	struct TreeNode* temp;
	if (root == NULL || (root->left == NULL && root->right == NULL))
	{
		return root;
	}
//	else if (root->left != NULL && root->right == NULL)
//	{
		root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
//		root->right = root->left;
//		root->right->left = root->right->right = root->left = NULL;
//	}
//	else if (root->right != NULL && root->left == NULL)
//	{
//		root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
//		root->left->val = root->right->val;
//		root->left->left = root->left->right = root->right = NULL;
//	}
	else
	{
		temp = root->left;
		root->left = root->right;
		root->right = temp;
	}
	root->left = invertTree(root->left);
	root->right = invertTree(root->right);	
}
int minDepth(struct TreeNode* root) {
	if (root == NULL )
	{
		return 0;
	}
	else if ((root->left == NULL && root->right == NULL))
	{
		return 1;
	}
	else if (root->left == NULL)
	{
		return minDepth(root->right) + 1;
	}
	else if (root->right == NULL)
	{
		return minDepth(root->left) + 1;
	}
	else
	{
		return (minDepth(root->left)> minDepth(root->right) ? minDepth(root->right) : minDepth(root->left)) + 1;
	}
}
int maxDepth(struct TreeNode* root) {
	int left, right;
	if (root == NULL)
	{
		return 0;
	}
	left = maxDepth(root->left);
	right = maxDepth(root->right);
	if (left == 0 && right == 0)
	{
		return 1;
	}
	return (left > right ? left : right) + 1;
}
这三道题都是比较简单的递归实现,但是编写时也出现了错误:

①树的镜像,左右树的交换,我最初想成了左右数值的交换,题目看懂了,但是想错了;

②第二三题可以用深度优先搜索算法(DFS),了解了一下 分层遍历,需要借助队列来实现,而递归都是默认的使用栈,C语言不好实现非递归方法;

③先做了第二题才做第三题,开始只是简单的改了min为max等,提交时发现超时;递归会占用栈,数据太多时会越界、效率也比较低,可以避免尽量避免,可能的用变量 代替;

④ leetcode 根的深度为1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值