爱程序网

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  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     
12     public int minDepth(TreeNode root) {
13         
14         Stack<Integer> stack=new Stack<>();
15         int depth=0;
16        if(root==null)
17        return 0;
18        
19        if(root.left==null&&root.right==null)
20        {return 1;}
21        
22        if(root.left!=null)
23        {
24            depth=1+minDepth(root.left);
25 26            if(stack.empty()||stack.peek()>depth)
27            stack.push(depth);
28        }
29        
30        
31         if(root.right!=null)
32        {
33            depth=1+minDepth(root.right);
34             if(stack.empty()||stack.peek()>depth)
35             stack.push(depth);
36        }
37       
38        return stack.peek();
39     }
40 }

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助