给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离
2.递归方法,类似于最大深度
3./**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: An integer
*/
int minDepth(TreeNode *root) {
// write your code here
if(root == NULL) return 0;
if(root->left == NULL) return minDepth(root->right) + 1;//斜左子树
if(root->right == NULL) return minDepth(root->left) + 1;//斜右子树
int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);
return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1);
}
};
4.感想
仿照最大深度写了个程序,本以为能通过,但是没过,后来想想,看了看同学的,知道了会出现左子树为空或者右子树为空的情况,改正后通过.