Leetcode 111: 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.

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int MinDepth(TreeNode root) {
12         if (root == null) return 0;
13         
14         if (root.left != null && root.right != null)
15         {
16             return Math.Min(MinDepth(root.left), MinDepth(root.right)) + 1;
17         }
18         else if (root.left != null)
19         {
20             return MinDepth(root.left) + 1;
21         }
22         else
23         {
24             return MinDepth(root.right) + 1;
25         }
26     }
27 }
28 
29 public class Solution1 {
30     public int MinDepth(TreeNode root) {
31         if (root == null) return 0;
32         
33         var minDepth = new int[1] {Int32.MaxValue};
34         DFS(root, 1, minDepth);
35         return minDepth[0];
36     }
37     
38     private void DFS(TreeNode node, int cur, int[] minDepth)
39     {
40         if (node.left == null && node.right == null)
41         {
42             minDepth[0] = Math.Min(cur, minDepth[0]);
43             return;
44         }
45         
46         if (node.left != null) DFS(node.left, cur + 1, minDepth);
47         if (node.right != null) DFS(node.right, cur + 1, minDepth);
48     }
49 }

 

posted @ 2017-11-18 05:04  逸朵  阅读(151)  评论(0)    收藏  举报