Leetcode 111

//最小深度要求的是到叶节点的距离,因此和最大深度还是有些不同的,需要多加两个判断条件,不然如果出现单侧有值的情况就不对了,例如[1,2]
/*
* * 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; if(!root->left) return 1+minDepth(root->right); if(!root->right) return 1+minDepth(root->left); return 1+min(minDepth(root->left),minDepth(root->right)); } };
原文地址:https://www.cnblogs.com/cunyusup/p/10339437.html