1.题目:求二叉树最小高度
【LeetCode111】:判断一棵二叉树的最小高度:
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.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
2.思路分析
起点就是 root 根节点,终点就是最靠近根节点的那个「叶子节点」嘛,叶子节点就是两个子节点都是 null 的节点。采用BFS,每一层结点同时入队列,找到叶子结点即终止。
注意:在加入叶子结点时,需左右分别独立判断是否加入队列。
3.源码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
//把指向节点的指针如队列
if(root==NULL) return 0;
queue<TreeNode* > save;
//记录步数:step
int step=1;
//根节点入队列
save.push(root);
while(!save.empty())
{
int qsize=save.size();
for(int i=0;i<qsize;i++)
{
TreeNode* new1=save.front();
save.pop();
if((new1->left==NULL)&&(new1->right==NULL))
return step;
else
{
if(new1->left!=NULL)
save.push(new1->left);
if(new1->right!=NULL)
save.push(new1->right);
}
}
step++;
}
return step;
}
};
4.递归算法求最小高度
注意:一定要抓住最小高度的判定条件!是出现叶子结点,即左右结点都为空。
因此不能单纯以左右节点最小值为最小高度路径,前提是左右节点均不空。
[2,null,3,null,4,null,5,null,6]该树结构比较特别
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
int left=minDepth(root->left);
int right=minDepth(root->right);
// cout<<root->val<<"当前值"<<endl;
if(left==0) return right+1;
else if(right==0) return left+1;
if(left>right)
return right+1;
else
return left+1;
}
};