题目考察的知识点是:
本题主要考察的是递归和二叉树。
题目解答方法的文字分析:
返回递归遍历二叉树的左边和遍历二叉树的右边深最小值。对于非叶子节点需对左右孩子判断,只返回不为空的节点。节点为空放回0。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public int minDepth (TreeNode root) {
// write code here
if (root == null) {
return 0;
}
ArrayList<Integer> arrayList = new ArrayList<>();
int count = 0;
Depth(root, arrayList, count);
int min = 1000;
for (int i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i) < min) min = arrayList.get(i);
}
return min + 1;
}
public void Depth (TreeNode root, ArrayList<Integer> arrayList, int count) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
arrayList.add(count);
return;
}
count++;
Depth(root.left, arrayList, count);
Depth(root.right, arrayList, count);
}
}

京公网安备 11010502036488号