[leetcode] minimum-depth-of-binary-tree

时间限制:1秒 空间限制:32768K 热度指数:96213
本题知识点: 

 算法知识视频讲解

题目描述

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  * 题意:找出根节点到叶子节点的最小深度
 3  * 注意:叶子节点必须是没有左右子树的节点,不能直接用二分递归。
 4 */
 5 /**
 6  * Definition for binary tree
 7  * public class TreeNode {
 8  *     int val;
 9  *     TreeNode left;
10  *     TreeNode right;
11  *     TreeNode(int x) { val = x; }
12  * }
13  */
14 //以下为错误解答:
15 // public class Solution {
16 //     int minDepth = 1<<20;
17 //     public int run(TreeNode root) {
18 //         find(root, 0);
19 //         return minDepth;
20 //     }
21 // 
22 //     public void find(TreeNode root, int depth){
23 //         if(root == null){
24 //             if(depth<minDepth){
25 //                 minDepth = depth;
26 //             }
27 //             return;
28 //         }
29 //         find(root.left,depth+1);
30 //         find(root.right,depth+1);
31 //     }
32 // }
33 public class Solution {
34     public int run(TreeNode root) {
35         if (root == null) return 0;
36         if (root.left == null || root.right == null) {
37             return run(root.left) + run(root.right) + 1;
38         }
39         else {
40             return 1 + Math.min(run(root.left), run(root.right));
41         }
42     }
43 }

猜你喜欢

转载自www.cnblogs.com/yfzhou/p/9781283.html