题目描述:

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 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int minDepth(TreeNode* root) {
13         if(!root)
14             return 0;
15         else if(!root->left)
16             return minDepth(root->right)+1;
17         else if(!root->right)
18             return minDepth(root->left)+1;
19         else
20             return min(minDepth(root->left),minDepth(root->right))+1;
21     }
22 };

 

posted on 2018-02-10 11:50  宵夜在哪  阅读(71)  评论(0编辑  收藏  举报