LeetCode刷题之路---111. 二叉树的最小深度
2019-04-20 14:46
337 查看
题目:给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
本题解题思路:可以想到用DFS和BFS以及递归,本文给出三种解决方法
第一种解决方法:BFS——广度优先搜索(相关内容可以参看BFS相关解析(转载))
解决方法:
[code]/** * 定义一树节点 * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.LinkedList; import javafx.util.Pair; class Solution { public int minDepth(TreeNode root) { if(root ==null){ return 0; } LinkedList<Pair<TreeNode,Integer>> queue=new LinkedList<Pair<TreeNode,Integer>>(); queue.addLast(new Pair<TreeNode,Integer>(root,1)); while(!queue.isEmpty()){ Pair<TreeNode,Integer> front =queue.removeFirst(); TreeNode cur=front.getKey(); int step = front.getValue(); if(cur.left==null&&cur.right==null){ return step; } if(cur.left!=null){ queue.addLast(new Pair<TreeNode,Integer>(root.left,step+1)); } if(cur.right!=null){ queue.addLast(new Pair<TreeNode,Integer>(root.right,step+1)); } } return -1; } }
思路:熟悉BFS的同学都知道,BFS遍历是可以求出最优解的,但需要借助一个队列,在Java中队列可以使用LinkedList表示,首先将树的根节点放入队列中,这里我们使用 LinkedList<Pair<TreeNode,Integer>>可以存进去一个(k,v);之后按照BFS的伪代码实现,然后判断队列是否为空,如果不为空,则取出队列的头元素,然后将与其关联的其他节点放进队列,同时更新step,最终便可以得到最短路径。(请注意此种解法,在leetcode上运行,说是运行超时,难受)
第二种解法:递归(本人理解递归乃是神器,奈何我是菜鸟一个,共同努力)
[code]/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int minDepth(TreeNode root) { if(root==null){ return 0; } int left =minDepth(root.left); int right =minDepth(root.right); //return Math.min(left,right)+1; if(left==0 || right==0){ return 1+left+right; } else{ return 1+Math.min(left,right); } } }
这里需要强调一个问题,我在刷题时的坑,一开始直接写的是return Math.min(left,right)+1;发现并不能全部ac,这种返回会忽略
1->2这种二叉树的正确性,原来的写法会得到返回值1,但其实正确答案是2,你可以研究下代码,很简单的,后来想了一个解决方法,如题。
第三种解法:万众瞩目的DFS(听说打过ACM的大佬说这个方法很重要,希望以后也能成为大神)
DFS学习链接可以参看这里DFS
参看递归。
相关文章推荐
- LeetCode 111. 二叉树的最小深度
- leetcode111. 二叉树的最小深度
- LeetCode写题历程——111. 二叉树的最小深度
- LeetCode - 111. 二叉树的最小深度
- [Leetcode] 104. 二叉树的最大深度与111. 二叉树的最小深度 java
- 【LeetCode】111. 二叉树的最小深度
- Leetcode 111. Minimum Depth of Binary Tree 二叉树最小深度
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度
- Leetcode039--二叉树的最小深度
- 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java
- Minimum Depth of Binary Tree 求二叉树最小高度/深度@LeetCode
- leetCode 笔记 ————二叉树最小深度
- Leetcode 最小二叉树深度和删除数组重复元素
- LeetCode 111 二叉树的最小深度
- LeetCode 111. Minimum Depth of Binary Tree (二叉树最小的深度)
- LeetCode:minimum-depth-of-binary-tree(二叉树最小深度)
- leetcode:minimum-depth-of-binary-tree(二叉树的最小深度)
- LeetCode || 二叉树的最小深度
- LeetCode 111. Minimum Depth of Binary Tree(二叉树最小深度)
- LeetCode Minimum Depth of Binary Tree 最小深度二叉树