LeetCode111.二叉树的最小深度(C语言)
2020-03-31 19:32
1181 查看
LeetCode111.二叉树的最小深度(C语言)
题目: https://leetcode-cn.com/problems/minimum-depth-of-binary-tree
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
返回它的最小深度 2.
思路:
定义一个step表示最短路径,遍历二叉树,只有访问但第一个叶子节点就可以return step;可以看做一个最短路径问题,那么就可以直接想到有两种方法——深度优先搜索(DFS)&&宽度优先搜索(BFS)。掌握两种所搜方式才是关键点。
方法一:
深度优先搜索:这个方法一般需要遍历整个树或者图,然后选出其中的最短路径,遍历整个二叉树,可以采用递归来完成。递归主要是要发现其中的重复子问题,找到这个,然后注意一些细节就可以了。一般代码都比较简洁。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int minDepth(struct TreeNode* root){ if(root==NULL) return 0; if(!root->left||!root->right) return minDepth(root->left)+minDepth(root->right)+1; else return (minDepth(root->left)<minDepth(root->right)?minDepth(root->left):minDepth(root->right))+1; }
方法二:
宽度优先搜索:对于寻找最短路径的题目,宽度优先搜索是个很好的选择,对于二叉树来说,就是层序遍历二叉树,从上至下一层一层的遍历,而这题又是求最小深度,所以可以用BFS搜索到第一个叶子结点就可以直接return step,就不用了像DFS一样遍历整个树了。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int minDepth(struct TreeNode* root){ struct TreeNode* que[5000]; struct TreeNode* temp; if(!root) return 0; int head=0,tail=0,step=0,i=0,size; que[tail++]=root; while(head<tail) { size=tail-head; step++; for(i=0;i<size;i++) { temp=que[head++]; if(!temp->left&&!temp->right) return step; if(temp->left) que[tail++]=temp->left; if(temp->right) que[tail++]=temp->right; } } return step; }
思路:就是每一次都对一层进行入队和出队,注意要在入队之前算出这一层的长度,然后在入队时判断是否是叶子节点。其他的都是一些入队出队的常规操作。
if(!temp->left&&!temp->right) return step;
总的来说,还是要理解DFS和BFS,只有理解透了才能应对各种题目,换句话说还是要多做题才能更好地理解。
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- leetcode 111-二叉树最小深度
- leetcode111_二叉树最小深度
- [LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
- leetcode之二叉树类之二叉树深度系列-----104/111/110/108/109 二叉树最大/最小深度/AVL树的判断和由有序序列生成(牵扯分治相关,OJ105/106)
- Leetcode 111 python 二叉树的最小深度
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- LeetCode-111.二叉树的最小深度(相关话题:深度优先)
- LeetCode:111_Minimum Depth of Binary Tree | 二叉树的最小深度 | Easy
- leetcode111:二叉树的最小深度(C++)
- 【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】
- LeetCode 111 二叉树的最小深度
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- LeetCode 111 二叉树的最小深度 Java 递归
- 利用python 完成leetcode111 二叉树的最小深度
- [leetcode]Maximum Depth of Binary Tree (求二叉树的最大深度 C语言)
- LeetCode——minimum-depth-of-binary-tree 二叉树的最小深度
- LeetCode 111 Minimum Depth of Binary Tree(二叉树的最短深度)(BT、DFS)(*)
- LeetCode 111. 二叉树的最小深度
- [LeetCode]111. Minimum Depth of Binary Tree--二叉树的最小深度
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)