题目描述
题目链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
思路
DFS
代码实现
class Solution {public int minDepth(TreeNode root) {return Depth(root);}public int Depth(TreeNode root){if(root==null){return 0;}int left = Depth(root.left);int right = Depth(root.right);//如果左子树或右子树的深度不为0,即存在一个子树,那么当前子树的最小深度就是该子树的深度+1if(left==0 || right==0){return left+right+1;}//如果左子树和右子树的深度都不为0,即左右子树都存在,那么当前子树的最小深度就是它们较小值+1return Math.min(left,right)+1;}
}
另一个写法:
class Solution {public int minDepth(TreeNode root) {sif(root==null) return 0;else if(root.left==null) return minDepth(root.right)+1;else if(root.right==null) return minDepth(root.left)+1;else return Math.min(minDepth(root.left), minDepth(root.right)) + 1;}
}