问题描述:
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。 样例给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
解题思路:分情况考虑,首先是空树的情况,然后只有一个节点的情况,然后考虑有其他情况,用递归来写。
代码:
/** * 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) { if(root==NULL) return 0; if(root->left==NULL&&root->right==NULL) return 1; if(root->left==NULL){ return minDepth(root->right)+1; } else if(root->right==NULL){ return minDepth(root->left)+1; } else{ int d=minDepth(root->left)+1; int e=minDepth(root->right)+1; if(e>d) return d; else return e;} // write your code here } };
感悟:
注意分情况时要全面考虑