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.
和Path Sum这题想法一样,DFS,两个Stack。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
Stack<TreeNode> nodeStack = new Stack<TreeNode>();
Stack<Integer> depthStack = new Stack<Integer>();
if(root == null)
return 0;
nodeStack.push(root);
depthStack.push(1);
int minDepth = Integer.MAX_VALUE;
while(!nodeStack.isEmpty()){
TreeNode node = nodeStack.pop();
int currDepth = depthStack.pop();
if(node.left == null && node.right == null){
if(currDepth < minDepth)
minDepth = currDepth;
}
if(node.left != null){
nodeStack.push(node.left);
depthStack.push(currDepth + 1);
}
if(node.right != null){
nodeStack.push(node.right);
depthStack.push(currDepth + 1);
}
}
return minDepth;
}
}