LeetCode OJ:Minimum Depth of Binary Tree(二叉树的最小深度)

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

求二叉树的最小深度,额,简单的递归而已,代码如下:

 1 class Solution {
 2 public:
 3     int minDepth(TreeNode* root) {
 4         if(root = NULL) return 0;
 5         int leftDep = minDepth(root->left);
 6         int rightDep = minDepth(root->right);
 7         if(leftDep == 0 && rightDep == 0) return 1;//叶子节点
 8         if(leftDep == 0) leftDep = INT_MAX;
 9         if(rightDep == 0) rightDep = INT_MAX;//中间节点
10         return min(leftDep, rightDep) + 1; 
11     }
12 };

java 版本的代码一样,与上面相同,代码如下所示:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int minDepth(TreeNode root) {
12         if(root == null) 
13             return 0;
14         int leftDep = minDepth(root.left);
15         int rightDep = minDepth(root.right);
16         if(leftDep == 0 && rightDep == 0)
17             return 1; //到达这里表明的是叶子节点
18         if(leftDep == 0) leftDep = Integer.MAX_VALUE;
19         if(rightDep == 0) rightDep = Integer.MAX_VALUE;
20         return Math.min(leftDep, rightDep) + 1;       
21     }
22 }
原文地址:https://www.cnblogs.com/-wang-cheng/p/4892902.html