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 }
原标题:111. Minimum Depth of Binary Tree
关键词: