leetcode-tree1
来源:互联网 发布:unity3d网络游戏开发 编辑:程序博客网 时间:2024/05/18 02:25
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
0 0
- leetcode-tree1
- java Tree1.1计算器
- EasyUi之Tree1
- amittai的B+tree1.12版本的dot输出补丁
- 判断一个节点是否在二叉树中,判断tree2是否为tree1的子树
- 判断一颗二叉树是是否是另一颗树的子树。比如tree2是tree1的子树
- 二叉树--判断一颗二叉树是是否是另一颗树的子树。比如tree2是tree1的子树。
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- FireDAC 下的 Sqlite [6] - 加密
- Android WiFi开发中遇到的问题
- bom问题,编码问题
- 几千万条数据,怎么让查询效率高起来?
- 对PAR DAR SAR的理解
- leetcode-tree1
- 多线程(高级篇
- 第一题
- SBJson的使用
- FireDAC 下的 Sqlite [7] - 备份、优化、事务(Transaction)
- magento搬家的方法
- NGUI在secene中看不到
- SAT数学解题方法:逻辑推理
- 期权的理解