https://www.bilibili.com/video/av46402848/
考虑的方面要谨慎
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null)
return 0;
if(root.left==null)
return minDepth(root.right)+1; //!!!!!关键 左子树为null 就看 右子树
if(root.right==null)
return minDepth(root.left)+1; //!!!!!关键 右子树为null 就看 左子树
int left = minDepth(root.left) +1;
int right = minDepth(root.right) +1;
return Math.min(left,right); //!!!!!关键
}
}
用链表实现 层次遍历
class Solution {
public int minDepth(TreeNode root) {
int res = 0;
if (root == null)
return res;
LinkedList<TreeNode> ll = new LinkedList<TreeNode>();
ll.add(root);
while (!ll.isEmpty()) {
int size = ll.size();
res++; // 要用两个while 的原因主要是增加层作用
while (size > 0) {
TreeNode temp = ll.poll();
if (temp.left == null && temp.right == null)
return res;
if (temp.right != null)
ll.add(temp.right);
if (temp.left != null)
ll.add(temp.left);
size--;
}
}
return res;
}
}