题目描述
给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
深度优先搜索:
如果是空节点,返回0
如果左右子树为空 返回1
如果左子树为空,则遍历右子树
如果右子树为空,则遍历左子树
如果左右子树都不为空,则选择左子树和右子树中较小深度的,并加1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
if(root.left == null && root.right == null){
return 1;
}
if(root.left == null){
return minDepth(root.right) + 1;
}
if(root.right == null){
return minDepth(root.left) + 1;
}
return Math.min(minDepth(root.left),minDepth(root.right)) +1;
}
}