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
原创粉丝点击