- 求二叉树的最小深度,是常见的一种二叉树算法问题,主要解决办法有两种,一种是使用递归求解,另一种是非递归方式求解。这里给出递归求解方法。递归方法需要判断左右子树是否为空,当左子树为空,返回右子树的的最小深度+1,当右子树为空,返回左子树的最小深度+1,当左右子树均不为空时,返回左子树与右子树最小深度+1。
- 问题来源于leetcode:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
- Java递归求解方法:
1 /**
2 * Definition for a binary tree node.
3 */
4 public class TreeNode {
5 int val;
6 TreeNode left;
7 TreeNode right;
8 TreeNode(int x) { val = x; }
9 }
10
11 class Solution {
12 public int minDepth(TreeNode root) {
13 if(null == root){
14 return 0;
15 }
16 if(root.left == null){
17 return minDepth(root.right)+1;
18 }
19 if(root.right == null){
20 return minDepth(root.left)+1;
21 }
22 return Math.min(minDepth(root.left), minDepth(root.right))+1;
23
24 }
25 }