广度+dfs可破;
但是注意一下官方的自底向上的思想,不止一次出现过;
自己想了一种判断深度提前剪枝;
/** * 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: void dfs(TreeNode* root,int& depth,int dep){ if(!root->left&&!root->right){ //叶子结点; depth=dep; return; } //超出深度; if(dep>=depth) return; if(root->left) dfs(root->left,depth,dep+1); if(root->right) dfs(root->right,depth,dep+1); } int minDepth(TreeNode* root) { int min_depth=INT_MAX; if(!root) return 0; dfs(root,min_depth,1); return min_depth; } };
class Solution { public: int minDepth(TreeNode *root) { if (root == nullptr) { return 0; } if (root->left == nullptr && root->right == nullptr) { return 1; } int min_depth = INT_MAX; if (root->left != nullptr) { min_depth = min(minDepth(root->left), min_depth); } if (root->right != nullptr) { min_depth = min(minDepth(root->right), min_depth); } return min_depth + 1; } };