使用深度优先搜索:时间复杂度O(n),空间复杂度O(logn)
/** * 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==NULL) return 1+minDepth(root->right); if(root->right==NULL) return 1+minDepth(root->left); //当左右子树都不为空时,深度按照小的算; return 1+min(minDepth(root->right),minDepth(root->left)); } };
精简版:
/** * 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; int leftDepth=minDepth(root->left); int rightDepth=minDepth(root->right); return (leftDepth==0 || rightDepth==0)? leftDepth+rightDepth+1:1+min(leftDepth,rightDepth); } };