Lintcode---二叉树的最小深度
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
思路:本来是很简单的一道题目,使用递归方法很容易求解,思路也清晰,但很久没AC。
反思,在考虑的时候不要被绕进去,从大的方面考虑,思路正确就可以。
另外,在debug时,直接通过测试用例来模拟程序过程,快速找到问题所在。
/**
* 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
*/
/*
思路:本来是很简单的一道题目,使用递归方法很容易求解,思路也清晰,但很久没AC。
反思,在考虑的时候不要被绕进去,从大的方面考虑,思路正确就可以。
另外,在debug时,直接通过测试用例来模拟程序过程,快速找到问题所在。
*/
int minDepth(TreeNode *root) {
// write your code here
if(root==NULL){
return 0;
}
if(root->right==NULL){
return minDepth(root->left)+1;
}
if(root->left==NULL){
return minDepth(root->right)+1;
}
return min(minDepth(root->left),minDepth(root->right))+1;
}
};
队列方式实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL){
return 0;
}
queue<TreeNode*> q;
q.push(root);
// root 本身就是一层,depth 初始化为 1
int depth = q.size();
while(!q.empty()){
int s = q.size();
/* 将当前队列中的所有节点向四周扩散 */
for(int i =0;i<s;i++){
/* 判断是否到达终点 */
TreeNode* temp=q.front();
q.pop();
if(temp->left==NULL && temp->right==NULL){
return depth;
}
/* 将相邻节点加入队列 */
if(temp->left!=NULL){
q.push(temp->left);
}
if(temp->right!=NULL){
q.push(temp->right);
}
}
/* 这里增加步数 */
depth++;
}
return depth;
}
};

浙公网安备 33010602011771号