1.二叉树的最小深度
思路
从根部开始遍历一棵二叉树,查看它是否有左右结点:
- 没有根结点,那结果就是0;
- 有根结点,没有左右子树,结果为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)return 0;//树为空
if(!(root->left) && !(root->right))return 1;//无左右子树
if(!(root->left))return minDepth(root->right)+1;
//无左子树,以右子树为根,看它的左右子树
else if(!(root->right))return minDepth(root->left)+1;//同上
else return 1+min(minDepth(root->left),minDepth(root->right));
}
};
改进精简版
class Solution {
public:
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
int left = minDepth(root->left), right = minDepth(root->right);
return (left && right) ? 1+min(left,right) : 1+left+right;
}
};