树——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. 当节点为叶节点时,深度为1;

2. 当节点只有左孩子(或右孩子)时,深度为左孩子(或右孩子)+1;

3. 当节点既有左孩子又有右孩子时, 深度为min(左孩子,右孩子)+1。

 

代码

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int run(TreeNode root) {
12         if(root==null)
13             return 0;
14         if(root.left==null && root.right==null)
15             return 1;
16         if(root.left==null && root.right!=null)
17             return run(root.right)+1;
18         if(root.left!=null && root.right==null)
19             return run(root.left)+1;
20         return Math.min(run(root.left), run(root.right))+1;
21     }
22 }

 

posted on 2017-08-18 11:16  一个不会coding的girl  阅读(251)  评论(0编辑  收藏  举报

导航