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.
题目链接:https://leetcode.com/problems/minimum-depth-of-binary-tree/
题目分析:分别往左往右,遇到叶子则更新答案
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void DFS(TreeNode root, int deep, int[] ans) {
if(root.left == null && root.right == null) {
ans[0] = Math.min(ans[0], deep);
return;
}
if (root.left != null) {
DFS(root.left, deep + 1, ans);
}
if (root.right != null) {
DFS(root.right, deep + 1, ans);
}
}
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int[] ans = new int[1];
ans[0] = Integer.MAX_VALUE;
DFS(root, 1, ans);
return ans[0];
}
}