[leetcode] Minimum Depth of Binary Tree
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.
https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
思路:递归实现,取左右节点中深度小的+1。
注意:如果左右子树其中一个为null,则应以不为null的子树深度为准,而不是以null的深度0为准。
public class Solution { public int minDepth(TreeNode root) { if (root == null) return 0; if (root.left == null) return minDepth(root.right) + 1; if (root.right == null) return minDepth(root.left) + 1; else { int minLeft = minDepth(root.left); int minRight = minDepth(root.right); return (minLeft < minRight ? minLeft : minRight) + 1; } } public static void main(String[] args) { TreeNode root = new TreeNode(10); root.left = new TreeNode(5); root.right = new TreeNode(5); root.right.left = new TreeNode(9); System.out.println(new Solution().minDepth(root)); } }
第二遍记录:注意各种终止情况的讨论。
public class Solution { public int minDepth(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 Math.min(minDepth(root.left),minDepth(root.right)) + 1; } }
第三遍记录:
思路完全参考第二遍,写之前画图分析各种情况。