LeetCode刷題Easy篇Minimum Depth of Binary Tree
阿新 • • 發佈:2018-12-05
題目
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its minimum depth = 2.
我的嘗試
遞迴解法
這個題目類似於求二叉樹的最大深度,先用遞迴方法解決:
/** * 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 minLeft=minDepth(root.left); int minRight=minDepth(root.right); if(minRight==0||minLeft==0) return minLeft+minRight+1; return 1+Math.min(minLeft,minRight); } }
我最開始的寫法,對於[1,2]這個情況不對,題目期待結果為2,我的是1,如果沒有節點,找到最近的葉子節點,所以增加了if判斷,如果left或者right為空的情況。
非遞迴解法
最大深度用的是BFS解法,這裡也用BFS解法嘗試一下。在發現left和right都為空的時候,這個深度應該就是最小深度。
/** * 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; Deque<TreeNode> queue=new LinkedList(); queue.add(root); int count=0; boolean isBreak=false; while(!queue.isEmpty()&&!isBreak){ int size=queue.size(); while(size-->0){ TreeNode treeNode=queue.poll(); if(treeNode.left==null&&treeNode.right==null){ isBreak=true; } if(treeNode.left!=null){ queue.addLast(treeNode.left); } if(treeNode.right!=null){ queue.addLast(treeNode.right); } } count++; } return count; } }